最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

[nodejs query in query result loop

网站源码admin32浏览0评论

[nodejs query in query result loop

[nodejs query in query result loop

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

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

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

2)item = {...项目,图像:行}在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)
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论