1 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
我相信您的代碼中的問(wèn)題出在user.products.map(...)函數(shù)上,因?yàn)槟肋h(yuǎn)不會(huì)等待您在地圖中創(chuàng)建的所有承諾都得到解決。
換句話(huà)說(shuō),該map函數(shù)返回一個(gè)待處理的 Promise 數(shù)組,但它不會(huì)等待它們完成,因此執(zhí)行會(huì)繼續(xù)執(zhí)行,直到到達(dá)res.status(...)任何代碼map執(zhí)行之前的其余代碼。
你有不同的選擇來(lái)解決它,但主要是你需要處理map函數(shù)返回的承諾數(shù)組并等待它們完成,然后再結(jié)束你的代碼。async/await在Google Developers Web 基礎(chǔ)指南中有一個(gè)很好的解釋如何處理這種情況。
我通常利用Promise.all()函數(shù),它從承諾數(shù)組中返回一個(gè)承諾,因此您可以等到代碼中的代碼為數(shù)組中的每個(gè)項(xiàng)目并行map執(zhí)行(即在您的情況下)。您可以在MDN 文檔中閱讀更多相關(guān)信息。product
// ...
let promisesArray = user.products.map(async product => {...});
// promisesArray should look like: [Promise { <pending> }, Promise { <pending> }, … ]
// Using Promise.all we wait for each of them to be done in parallel
await Promise.all(promisesArray);
// Now you are certain the code in the map has been executed for each product
// ...
一個(gè)好的做法是使用try {} catch(err) {}塊Promise.all()來(lái)處理某些承諾被拒絕的情況
添加回答
舉報(bào)