NodeJS async.parallel在另一个async.parallel内

时间:2016-02-17 04:19:14

标签: node.js asynchronous

在node.js中,我希望在另一个内部有一个foreach async.parallel。但是我得到了“回调已被调用”错误(查看我的代码的评论)。我希望回调到外部只在内部完成后调用。我怎么能这样做?

async = require("async");

var asyncTasks = [];
var items = [];
/* push elements to items */

items.forEach(function(item){  
  var asyncTasks2 = [];
  var items2 = [];
  asyncTasks.push(function(callback2){
    item.someAsyncCall(function(){
       /* push elements to items2 */
       items2.forEach(function(item2){  
          item2.someAsyncCall(function(){
            callback2();          
          })
       }
       asyncTasks2.push(function(callback2){
         setTimeout(function(){
           callback2();
         }, 100000);
       });
       async.parallel(asyncTasks2, function(){
          // All tasks are done now
          doSomethingOnceAllAreDone();
          callback(); // callback was already called
        });
    });
  });
});


asyncTasks.push(function(callback){
  setTimeout(function(){
    callback();
  }, 100000);
});

async.parallel(asyncTasks, function(){
  // All tasks are done now
  doSomethingOnceAllAreDone();
});

1 个答案:

答案 0 :(得分:0)

使用bluebird promise

var Promise = require('bluebird');
var items = [];
return Promise.map(items, function(item){
    var items2 = [];
    return Promise.map(items2, function(item2){
        return item2.someAsyncCall();
    })
    .then(function(){
        return doSomethingOnceItems2AreDone();        
    }); 
})
.then(function(){
    return doSomethingOnceItems1AreDone();    
});