Search code examples
node.jsnested-loopsasync.js

nodejs Async.each Nested loop Confusion


i want to have two nested for loops

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

Now i expect an output Like { InnerLoopFinished OuterLoopFinished } according to List Size and

process Finsished

Bt what i get is Process Finished at First and InnerLoop and Outerloop message depending upon loop size..

Im process data in both loops so when control goes to print "final process" message i expect all my data is populated to an Object Before that and send it as a response which isnt achieved here

I think imnt not clear about idea of working async.each..Can someone help me to achieve the desired output


Solution

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