Parallel tasks and task series with the Async.js library
Another approach to deal with asynchronous calls is a library called Async.js (https://github.com/caolan/async). When using this library, we can explicitly specify how we want the batch of tasks to be resolved—as a waterfall (chain) or in parallel.
In the first case, we can supply an array of callbacks to async.waterfall
, assuming when one is completed, the next one is invoked. We can also pass the resolved value from one callback to another and receive the aggregate value or the thrown exception in a method's on-done
callback:
/** * Concat given arguments * @returns {String} */ function concat(){ var args = [].slice.call( arguments ); return args.join( "," ); } async.waterfall([ function( cb ){ setTimeout( function(){ cb( null, concat( "foo" ) ); }, 10 ); }, function( arg1, cb ){ setTimeout( function(){ cb( null, concat( arg1, "bar" ) ); }, 0 ); }, function( arg1...