在for循环中使异步函数串联运行

时间:2016-08-05 12:28:31

标签: node.js for-loop asynchronous

所以在Node.js中假设我有以下代码:

for (var i = 0; i < 1000; i++) {
    someAsynchronousFunction(function(err,res) {
        // Do a bunch of stuff
        callback(null,res);
    });
}

但我想让它同步运行。我知道在Node JS中不建议这样做,但我只是想了解这种语言。我尝试实现以下解决方案,但它最终会在运行时挂起:

for (var i = 0; i < 1000; i++) {
    var going = true;
    someAsynchronousFunction(function(err,res) {
        // Do a bunch of stuff
        callback(null,res);
        going = false;
    });
    while (going) {

    }
}

出了什么问题以及这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

最好的方法之一是使用 async 库。

async.timesSeries(1000, function(n, next){
    someAsynchronousFunction(next);
});

或者你可以使用async.series() function

.times()文档: http://caolan.github.io/async/docs.html#.timesSeries

答案 1 :(得分:1)

另一种方法是使用Promises通过Array#reduce生成顺序执行它们:

// Function that returns Promise that is fllfiled after a second.
function asyncFunc (x){
  return new Promise((rs, rj)=>{
    setTimeout( ()=>{
      console.log('Hello ', x);
      rs();
    }, 1000)
  });
}
// Generate an array filed with values : [0, 1, 2, 3, ...]
Array.from({length : 1000}, (el, i)=> i)
// loop througth the array chaining the promises.
.reduce( (promise, value) => 
   promise.then(asyncFunc.bind(null, value))
, Promise.resolve(null));

相关问题