简体   繁体   中英

nodejs async.parallel recursion

I am test async.parallel behaviour with nodejs.

 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. The first call the parallel waits for the longest sleep which is 110 ms. The second call for same reason waits for 20 ms. Your code waits minimum 110 + 20 = 130 ms before writes a message: "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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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