gpt4 book ai didi

javascript - 在 Node.js 循环中等待 Promise,然后再进入下一个迭代

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:11 25 4
gpt4 key购买 nike

我在node.js中有以下循环

for (var i in details) {
if (!details[i].AmntRcvd > 0) {
res.sendStatus(400);
return;
}

totalReceived += details[i].AmntRcvd;
UpdateDetail(details[i].PONbr, details[i].LineID).then((results) => {
console.log(results);
details[i].QtyOrd = results.QtyOrd;
details[i].QtyRcvd = results.QtyRcvd;
details[i].QtyPnding = results.QtyPnding;
details[i].UnitCost = results.UnitCost;
}).catch((error) => {
console.log(error);
});
}

UpdateDetail 函数返回一个 promise 。在继续循环的下一次迭代之前,如何等待 promise 解决/拒绝。

最佳答案

您可以使用await关键字来解决这个问题。更多信息here

async function main() {
for (var i in details) {
if (!details[i].AmntRcvd > 0) {
res.sendStatus(400);
return;
}

try {
totalReceived += details[i].AmntRcvd;
let results = await UpdateDetail(details[i].PONbr, details[i].LineID);
console.log(results);
details[i].QtyOrd = results.QtyOrd;
details[i].QtyRcvd = results.QtyRcvd;
details[i].QtyPnding = results.QtyPnding;
details[i].UnitCost = results.UnitCost;
}
catch(e) {
console.log(error);
}
}
}

关于javascript - 在 Node.js 循环中等待 Promise,然后再进入下一个迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60504577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com