javascript NodeJS,Async forEachSeries 执行顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15942832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS, Async forEachSeries execution order
提问by ericbae
Just trying to get my head around using Async module for NodeJS.
只是想弄清楚使用 NodeJS 的 Async 模块。
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?
我该如何解决?
回答by spotirca
The forEachMethod also accepts a callback when everything done. So your code should look like this:
当一切都完成时, forEachMethod 也接受回调。所以你的代码应该是这样的:
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.
您代码中的问题是您假设 async.forEachSeries 是同步的,但事实并非如此。它保证了数组将被同步处理的事实,但函数本身是异步的。