Reputation: 13588
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
Upvotes: 3
Views: 3074
Reputation: 330
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)
});
Upvotes: 3