【问题标题】:Waiting for Promise before moving to next iteration in a loop in Node.js在 Node.js 的循环中移动到下一个迭代之前等待 Promise
【发布时间】:2018-08-24 15:40:44
【问题描述】:

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

【问题讨论】:

  • 仅供参考:不推荐使用for..in(尤其是在阵列上)。将for..of 用于数组,将for..ofObject.keys()Object.values()Object.entries() 一起用于对象。

标签: javascript node.js


【解决方案1】:

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

【讨论】:

  • @Ze Rebeus,我错了,但这是你异步工作的方式。
【解决方案2】:

你可以使用等待:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2018-02-08
      相关资源
      最近更新 更多