Waiting for Promise before moving to next iteration in a loop in Node.js

Viewed 1701

I have the following loop in 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);
  });
}

The UpdateDetail function returns a promise. How do I wait for the promise to resolve/reject before moving on to the next iteration of the loop.

3 Answers

You can use the await keyword to solve this. more info 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);
    }
  }
}

You can use 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)
}

Here's the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

You can use async library for this.then go for async.eachSeries.

You need to do npm install async first

Here is the example:

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