我正在使用nodejs测试async.parallel行为。
var async = require("async");
function makeSleepFunction(i) {
return function(callback) {
setTimeout(function() {
console.log(' + sleep '+i);
callback(null, i);
}, i);
}
}
function parallel(i, callback) {
// console.log('----parallel '+i+'-----')
return async.parallel([makeSleepFunction(i), makeSleepFunction(i+10)], callback);
}
// Expected result OK: 100 before 10
parallel(100, function(err, results) {
console.log('async.parallel 1 done: '+results.toString());
parallel(10, function(err, results) {
console.log('async.parallel 2 done: '+results.toString());
});
});
// Expected result KO: 100 after 10
setTimeout(function() { // Wait the 1st test is finished
console.log('\n\n***** The followig test des not give the expected result:')
parallel(100,
parallel(10, function(err, results) {
console.log('async.parallel 2 done: '+results.toString());
})
);
}, 300);
有人可以用第二次测试解释没有给出预期的结果吗?
感谢帮助。
异步并行等待每个完成的任务。您的任务定时为i和i + 10。并行的第一个调用等待最长的睡眠时间,即110 ms。出于相同原因的第二个呼叫将等待20毫秒。您的代码至少等待110 + 20 = 130毫秒,然后再写一条消息:“ async.parallel 2 done”
在第二个测试中,您没有传递回调,但是立即调用了一个新的并行函数。尝试这种方式:
setTimeout(function() { // Wait the 1st test is finished
console.log('\n\n***** The followig test des not give the expected result:')
parallel(100,function(){ //not call, but only declare a function
parallel(10, function(err, results) {
console.log('async.parallel 2 done: '+results.toString());
})
});
}, 300);
或者你当然可以使用bind
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句