我從存盤在 mongodb 資料庫中的陣列欄位中獲取幾個 id,并將這些值作為陣列存盤到一些常量變數中。現在我使用 map 函式遍歷陣列并基于這些 id 在 map 中執行一些查詢操作函式,當我得到結果時,我將它存盤在新陣列中,然后我試圖將該新陣列回傳給用戶。
下面是我的代碼:
const data = await userSchema.findOne({_id:objectId,active:true});
const hubIdArray = data.hubs; //Here storing all the ids getting from db array field
const hubs = []; //Storing values here after performing query opseration inside map function
hubIdArray.map(async (hubId) => {
const hub = await hub_schema.findOne({id:hubId});
hubs.push(hub);
console.log(hubs); // Here I am getting the hubs array.
})
console.log('Out',hubs); // But here its returning an empty array
return res.send(hubs);
為什么即使我在 map 函式之外宣告了一個空的 hubs 陣列,我也會在 map 函式內部而不是在 map 函式外部獲取陣列。有人告訴我。
uj5u.com熱心網友回復:
您的map功能async基本上就是您console.log('Out',hubs)在檢索完成之前的運行。解決此問題的最簡單方法是將其更改map為標準for回圈。
const hubs = [];
for (let i = 0; i < hubIdArray.length; i ) {
const hub = await hub_schema.findOne({id:hubIdArray[i]});
hubs.push(hub);
console.log(hubs);
}
console.log('Out',hubs);
return res.send(hubs);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528252.html
