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

时间:2018-08-24 15:40:45

标签: javascript 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。在进入下一个循环迭代之前,我如何等待承诺解决/拒绝。

3 个答案:

答案 0 :(得分:2)

您可以使用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);
    }
  }
}

答案 1 :(得分:0)

您可以使用await:

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

  totalReceived += details[i].AmntRcvd;
  await 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);
  });
  console.log('done with ' + i)
}

以下是文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

答案 2 :(得分:0)

您可以为此使用异步库。然后选择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
})