nodejs async.parallel 递归

nodejs async.parallel recursion

我正在使用 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 毫秒。 出于同样原因的第二次调用等待 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