【发布时间】:2017-05-03 09:50:22
【问题描述】:
我正在测试由 async.parallel 函数调用的回调:如果回调使用参数或不使用参数,执行流程似乎有所不同。
var async = require("async");
function makeTestFunction(i) {
return function(callback) {
console.log('test Function: '+i);
return callback();
};
}
function test(callback) {
var endFunctions = function(i) {
console.log('ending: ' + i);
return callback();
};
var testFunctions = [];
for (var i=0; i < 3; i++) {
console.log('loop: '+i);
testFunctions.push(makeTestFunction(i));
}
return async.parallel(testFunctions, endFunctions );
}
test( function() {
console.log('--------------- end test 1');
});
// loop: 0
// loop: 1
// loop: 2
// test Function: 0
// test Function: 1
// test Function: 2
// ending: null
// --------------- end test 1
结果如我所料:在所有函数完成后调用“endFunctions”回调。
现在我希望匿名函数回调返回一个值:
var async = require("async");
function makeTestFunction(i) {
return function(callback) {
console.log('test Function: '+i);
return callback(i);
};
}
function test(callback) {
var endFunctions = function(i) {
console.log('ending: ' + i);
return callback();
};
var testFunctions = [];
for (var i=0; i < 3; i++) {
console.log('loop: '+i);
testFunctions.push(makeTestFunction(i));
}
return async.parallel(testFunctions, endFunctions );
}
test( function() {
console.log('--------------- end test 2');
});
// loop: 0
// loop: 1
// loop: 2
// test Function: 0
// test Function: 1
// ending: 1
// --------------- end test 2
// test Function: 2
阅读async.parralel manual,我期待:
- 在所有匿名函数终止后调用一次回调“endFunctions”
- 回调“endFunctions”接收匿名函数返回的所有值的数组。
请问,有人能解释一下发生了什么,出了什么问题吗?
【问题讨论】:
-
我不确定这个问题是否重复。这并不明显。请仔细阅读
-
问题是关于 async.parallel (nodejs)
标签: javascript node.js callback async.js