亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

查詢結果循環中的 nodejs 查詢

查詢結果循環中的 nodejs 查詢

RISEBY 2022-08-04 09:50:33
我正在使用nodejs/mysql執行mysql查詢。在第一個結果集之后,我將遍歷結果集并查詢第二個表。1)為什么“for”有效而“foreach”不起作用?實現所需內容的正確循環方式是什么?2) 項目 = { ...item, images: rows } 在 getImage 函數中也不起作用,為什么?3)如何讓控制臺.log顯示修改后的結果?如果我使用“await”,控制臺.log(行)應該顯示修改后的結果,對嗎?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
查看完整描述

2 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

您必須將每個項目的正確處理程序傳遞給 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)

});


查看完整回答
反對 回復 2022-08-04
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

因為 forEach 沒有返回任何內容。所以最好使用 Array#map

http://img1.sycdn.imooc.com//62eb261100018ac506490262.jpg

rows = rows.map(getImages)



查看完整回答
反對 回復 2022-08-04
  • 2 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號