NodeJS Async forEachSeries execution order

Just trying to develop my head using the Async module for NodeJS.

I have the following code.

var a1 = [1,2,3,4,5,6,7,8]; async.forEachSeries(a1, function(n1, callback) { console.log(n1); var a2 = [10,11,12,13,14]; async.forEachSeries(a2, function(n2, callback) { console.log(n1 + " " + n2); callback(); }); callback(); }); 

I want to make the process of the above code so that the printout becomes

 1 1 10 1 11 1 12 1 13 1 14 2 2 10 2 11 2 12 2 13 2 14 3 3 10 3 11 3 12 3 13 3 14 ..... 

But instead, I get something like.

 1 1 10 2 2 10 1 11 3 3 10 2 11 1 12 .... 

How to fix it?

+6
source share
1 answer

ForEachMethod also accepts a callback when done. Therefore, your code should look like this:

 var a1 = [1,2,3,4,5,6,7,8]; async.forEachSeries(a1, function(n1, callback_s1) { console.log(n1); var a2 = [10,11,12,13,14]; async.forEachSeries(a2, function(n2, callback_s2) { console.log(n1 + " " + n2); callback_s2(); }, function () { /* Finished the second series, now we mark the iteration of first series done */ callback_s1(); } ); }); 

The problem with your code is that you assume that async.forEachSeries is synchronous, but it is not. This ensures that the array is processed synchronously, but the function itself is asynchronous.

+10
source

All Articles