繁華開(kāi)滿(mǎn)天機(jī)
2023-12-14 15:08:05
我正在編寫(xiě)一個(gè)函數(shù),通過(guò)查詢(xún)數(shù)據(jù)庫(kù)獲取價(jià)格,然后將其乘以數(shù)量來(lái)計(jì)算總金額。它對(duì)數(shù)組中的每一項(xiàng)執(zhí)行此操作,并將總數(shù)推送到一個(gè)數(shù)組,然后將其減少為返回的最終總數(shù)。函數(shù)如下圖所示:const calculateOrderAmount = async (items: cartProduct[]): Promise<number> => { const priceArray: number[] = []; items.forEach(async (p: cartProduct) => { const product = await Product.findById(p.prodId).exec(); if (product) { const totalPrice = product.price * p.quantity; priceArray.push(totalPrice) } else return; }); let amount; if (priceArray.length === 0) amount = 0; else amount = priceArray.reduce((a, b) => a + b); return amount;};我遇到的問(wèn)題是它的異步性。我希望它等待forEach完成,但由于它是異步的,它會(huì)繼續(xù)執(zhí)行函數(shù)的其余部分,因此最終返回 0。有沒(méi)有辦法讓它等待完成forEach?或者我應(yīng)該以不同的方式重寫(xiě)它
2 回答

蠱毒傳說(shuō)
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以嘗試以下for await of
構(gòu)造:
for await (variable of iterable) { statement }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

慕姐8265434
TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
通過(guò)使用forEach回調(diào),您可以創(chuàng)建一系列單獨(dú)的承諾,但forEach調(diào)用本身不會(huì)等待這些承諾。
簡(jiǎn)單的解決方案是使用循環(huán)for,它不使用回調(diào)系統(tǒng):
for (let p: cartProduct of items) {
const product = await Product.findById(p.prodId).exec();
if (!product) continue;
const totalPrice = product.price * p.quantity;
priceArray.push(totalPrice);
}
添加回答
舉報(bào)
0/150
提交
取消