admin管理员组文章数量:1357220
Just trying to get my head around using 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 in such a way that the print out 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'm getting something like..
1
1 10
2
2 10
1 11
3
3 10
2 11
1 12
....
How do I fix this?
Just trying to get my head around using 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 in such a way that the print out 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'm getting something like..
1
1 10
2
2 10
1 11
3
3 10
2 11
1 12
....
How do I fix this?
Share Improve this question edited Aug 4, 2013 at 12:07 Bergi 665k161 gold badges1k silver badges1.5k bronze badges asked Apr 11, 2013 at 7:18 ericbaeericbae 9,64426 gold badges77 silver badges109 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 17The forEachMethod also accepts a callback when everything done. So 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 in your code is the fact that you assume async.forEachSeries to be synchronous, but it is not. It guarantees the fact the array will be handled synchronously, but the function itself is asynchronous.
本文标签: JavaScriptNodeJSAsync forEachSeries execution orderStack Overflow
版权声明:本文标题:javascript - NodeJS, Async forEachSeries execution order - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739410367a2162027.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
process.stdout
, and thereforeconsole.log
as well, so that might result in different output. AndforEachSeries
is synchronous in that the next iteration will only be called once the previous is done. – robertklep Commented Apr 11, 2013 at 7:44(N+1)
only gets called once(N)
has completed. – robertklep Commented Apr 11, 2013 at 8:30