簡體   English   中英

在 Node.js 的循環中移動到下一次迭代之前等待 Promise

[英]Waiting for Promise before moving to next iteration in a loop in 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 函數返回一個承諾。 在進入循環的下一次迭代之前,我如何等待承諾解決/拒絕。

您可以使用await關鍵字來解決此問題。 更多信息在這里

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);
    }
  }
}

您可以使用等待:

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

您可以為此使用異步庫。然后使用 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
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM