1

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

4
  • It is asynchronous. Asynchronous functions return immediately without waiting to process anything. That's why "Process Finished" is printed first. That's the whole point of callbacks and promises. They get called when the process finishes so that you can insert code to do what you want when that happens. Commented Jan 24, 2017 at 9:00
  • @slebetman so how can i solve my issue ? ... the single loop works fine in serial mode using asyn.each ... But for nested loop it doesnt work like i desired .... Commented Jan 24, 2017 at 9:12
  • First, you have a typo I think. You have two variables called callback1 and none called callback Commented Jan 24, 2017 at 9:23
  • Also, I don't think your braces match. You seem to be missing some closing braces. Commented Jan 24, 2017 at 9:24

1 Answer 1

6
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');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot .. was abt to post that i got solution by the same method u did .. Bit late ..bt thanks again @mustafa

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.