简体   繁体   中英

nodejs query in query result loop

I'm performing mysql query using nodejs/mysql.

After the first result set, I will loop through the results set and query a second table.

1) Why 'for' works and 'foreach' doesn't? What's the proper looping way to achieve what I need?

2) item = {...item, images: rows } in the getImage function also doesn't work, why?

3) How to let the console.log show the modified results? If I use 'await', the console.log(rows) should show the modified results right?

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

You have to pass to the foreach method the proper handler on each item:

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

Plus, if you want to get the images on another array you should use map, its cleaner:

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

Because forEach not returning anything.So better use Array#map

在此处输入图像描述

rows = rows.map(getImages)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM