nodejs Async.each嵌套循环混淆

时间:2017-01-24 08:54:26

标签: node.js nested-loops async.js

我希望有两个嵌套的for循环

async.each(ListA,
function(itemA,callback1){
        //process itemA
        async.each(itemA.Children,
        function(itemAChild,callback1){
              //process itemAChild  
              callback1();
               }),
    function(err){
    console.log("InnerLoopFinished")
    }   

callback();
}),function(err){
console.log("OuterLoopFinished")
}
console.log("Process Finished")

现在我期待输出像 { InnerLoopF​​inished OuterLoopF​​inished 根据列表大小和

处理Finsished

但我得到的是 流程首先完成 和InnerLoop和Outerloop消息取决于循环大小..

我在两个循环中处理数据,所以当控制进入打印“最终进程”消息时,我希望我的所有数据都填充到一个对象之前,并将其作为响应发送到此处

我认为不清楚工作async.each的想法。有人帮我实现所需的输出

1 个答案:

答案 0 :(得分:4)

async.each(ListA, function (itemA, callback) { //loop through array
    //process itemA
  async.each(itemA.Children, function (itemAChild, callback1) { //loop through array
    //process itemAChild
    callback1(); 
    }, function(err) {
      console.log("InnerLoopFinished");
      callback();
    });
  }, function(err) {
    console.log("OuterLoopFinished");
    console.log('Process Finished');
});