【问题标题】:nodejs query in query result loop查询结果循环中的nodejs查询
【发布时间】:2020-08-20 23:57:41
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript mysql node.js


    【解决方案1】:

    您必须将每个项目的正确处理程序传递给 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)
    });
    

    【讨论】:

    • 然后首先,确保第一个函数工作正常:

      ``` ```
    • 然后首先,确保第一个函数正常工作:

      `` const getImages = async (item, key) => { let sql = await connection.format( 'SELECT * from images WHERE id = ?', [item.id]); ... console.log(">>> Get image Return: ", item) // 添加这一行 ... } ```

      然后确保您正在接收数据:

      ... var [行,字段] = await connection.execute(sql); console.log(">> Rows: ", rows) // 添加这一行 console.log(">> fields: ", fields) // 添加这一行 ... ``
    • 我的功能正常工作。我会坚持 for 循环,因为没有有效的 .map 解决方案
    • 您使用的是哪个 SQL 库?
    • 我正在使用 mysql2 nodejs。
    【解决方案2】:

    因为forEach没有返回任何东西。所以最好使用Array#map

    rows = rows.map(getImages)
    

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多