Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...