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

前端 未结 3 483
醉梦人生
醉梦人生 2020-12-21 11:10

I have the following loop in node.js

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

  totalReceived          


        
3条回答
  •  醉梦人生
    2020-12-21 11:56

    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

提交回复
热议问题