我正在編寫一個函數,通過查詢數據庫獲取價格,然后將其乘以數量來計算總金額。它對數組中的每一項執行此操作,并將總數推送到一個數組,然后將其減少為返回的最終總數。函數如下圖所示: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;};我遇到的問題是它的異步性。我希望它等待forEach完成,但由于它是異步的,它會繼續執行函數的其余部分,因此最終返回 0。有沒有辦法讓它等待完成forEach?或者我應該以不同的方式重寫它
是否可以在繼續之前等待內部“await”?
繁華開滿天機
2023-12-14 15:08:05