简体   繁体   English

Node.js异步并行递归

[英]nodejs async.parallel recursion

I am test async.parallel behaviour with nodejs. 我正在使用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); 

Can somebody explain with the second test does not give the expected result? 有人可以用第二次测试解释没有给出预期的结果吗?

Thanks for help. 感谢帮助。

The async parallel waits for every task done. 异步并行等待每个完成的任务。 Your tasks are timed i and i+10. 您的任务的时间是i和i + 10。 The first call the parallel waits for the longest sleep which is 110 ms. 并行的第一个调用等待最长的睡眠时间,即110 ms。 The second call for same reason waits for 20 ms. 出于相同原因的第二次呼叫等待20 ms。 Your code waits minimum 110 + 20 = 130 ms before writes a message: "async.parallel 2 done" 您的代码等待至少110 + 20 = 130毫秒,然后再写一条消息:“ async.parallel 2 done”

In the second test you not pass a callback, but you call imediately a new parallel function. 在第二个测试中,您没有传递回调,但是立即调用了一个新的并行函数。 try this way: 尝试这种方式:

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);

or you can use bind, of course 或者您当然可以使用绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM