我有一個array的items,我想追加一個異步值getProductMinQuantity。
問題是渲染res.status(200)...是在 item.order_quantity_minimum 被編輯之前發送的。
我認為像下面這樣的地圖會創建一個更新專案的新承諾。
newResult是一種型別Promise<any>[] | undefined,我無法在其中.then .catch執行我res.status的操作。
const getCart = async () => {
...
let newResult = result.data?.line_items.physical_items.map(async (item: any) =>
item.order_quantity_minimum = await getProductMinQuantity(item.product_id)
)
res.status(200).json({
data: result.data ? normalizeCart(result.data) : null,
})
}
有沒有想過我該如何安排?
uj5u.com熱心網友回復:
經典問題;您不能await在同步陣列方法(map、forEach、filter 等)中使用。相反,使用for...of回圈。
let newResult = []
for(let item of result.data?.line_items.physical_items) {
item.order_quantity_minimum = await getProductMinQuantity(item.product_id)
newResult.push(item);
}
// Do something with newResult
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370355.html
標籤:javascript 打字稿 异步 异步等待 承诺
上一篇:Dart中的異步編程不起作用
