javascript - 查询结果循环中的nodejs查询

标签 javascript mysql node.js

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

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

1) 为什么“for”有效而“foreach”无效?实现我需要的正确循环方式是什么?

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

3) 如何让console.log显示修改后的结果?如果我使用 'await',console.log(rows) 应该显示修改后的结果吧?

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

最佳答案

您必须将每个项目的正确处理程序传递给 foreach 方法:

let new_rows = Array()
rows.forEach(row => {
    new_rows.push(await getImages(row, i))
});

另外,如果你想在另一个阵列上获取图像,你应该使用 map ,它更干净:

let new_rows = rows.map(row => {
    return await getImages(row, i)
});

关于javascript - 查询结果循环中的nodejs查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61628128/

相关文章:

javascript - 连接ECONNREFUSED 127.0.0.1 :21 error in node js

javascript - AngularJS:$q.defer() 不能被工厂方法共享

mysql - 将一行复制到另一个表并创建新的时间戳

mysql - 将地理空间点转换为纬度/经度字段

php,MySQL - while 循环并保存到记录

javascript - 未设置 Node process.timezone

javascript - 使用 Google Translate V2 进行回调

javascript - 如何从呈现的 HTML 模板呈现 JS 模板?

javascript - 如何使用 React-bootstrap 进行多输入表单验证?

javascript - 数组 forEach 传递 "push"作为参数