一尘不染

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

node.js

我在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。在继续循环的下一个迭代之前,我如何等待承诺解决/拒绝。


阅读 265

收藏
2020-07-07

共1个答案

一尘不染

您可以为此使用异步库。然后转到async.eachSeries。

您需要先执行npm install async

这是示例:

var async = require('async');
async.eachSeries(yourarray,function(eachitem,next){
// Do what you want to do with every for loop element
next();
},function (){
//Do anything after complete of for loop
})
2020-07-07