查询结果循环中的 nodejs 查询

我正在使用nodejs/mysql执行mysql查询。

在第一个结果集之后,我将遍历结果集并查询第二个表。

1)为什么“for”有效而“foreach”不起作用?实现所需内容的正确循环方式是什么?

2) 项目 = { ...item, images: rows } 在 getImage 函数中也不起作用,为什么?

3)如何让控制台.log显示修改后的结果?如果我使用“await”,控制台.log(行)应该显示修改后的结果,对吗?

const getImages = async (item, key) => {

    let sql = await connection.format('SELECT * from `images` WHERE id = ?', [item.id]);

    const [ rows , fields ] = await connection.execute(sql);


    item['images'] = rows

    item = { ...item, images: rows } //'<-- this method doesn't work.


    return item

}


let sql = await connection.format(`SELECT * from table ORDER BY a.listing_id LIMIT ?,?`, [0,10])


    var [rows, fields] = await connection.execute(sql);


    // rows.forEach(getImages)   //'<-- this does not work when uncommented

    // rows = rows.forEach(getImages) //'<-- this also does not work when uncommented.


    for (let i = 0; i < rows.length; i++) {    //'<-- but this works

        rows[i] = await getImages(rows[i], i);

    }


    console.log(rows) //<----- this doesn't show modified results on terminal console

    res.json(rows) //<----- browser can see the modified results on browser console




RISEBY
浏览 100回答 2
2回答

慕姐8265434

您必须将每个项目的正确处理程序传递给 foreach 方法:let new_rows = Array()rows.forEach(row => {&nbsp; &nbsp; new_rows.push(await getImages(row, i))});另外,如果你想在另一个数组上获取图像,你应该使用map,它更干净:let new_rows = rows.map(row => {&nbsp; &nbsp; return await getImages(row, i)});

繁星coding

因为&nbsp;forEach&nbsp;没有返回任何内容。所以最好使用&nbsp;Array#maprows&nbsp;=&nbsp;rows.map(getImages)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript