等待Promise,然后再进入Node.js循环中的下一个迭代 [英] Waiting for Promise before moving to next iteration in a loop in Node.js

查看:60
本文介绍了等待Promise,然后再进入Node.js循环中的下一个迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

UpdateDetail函数返回一个Promise.在继续循环的下一个迭代之前,我如何等待承诺解决/拒绝.

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.

推荐答案

您可以为此使用异步库.然后选择async.eachSeries.

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

您需要先执行npm install async

You need to do npm install async first

这里是示例:

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

这篇关于等待Promise,然后再进入Node.js循环中的下一个迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆