Node.js
Async for Node.js
Async module for node.js saves the day when it comes to synchronizing asynchronous tasks, or executing them in a serial manner.
To execute tasks in order, you can use the series method.
var async = require('async'); var somethingAsynchronous = function(callback) { console.log('Called something asynchronous'); callback(); }; var somethingElseAsynchronous = function(callback) { console.log('called something else asynchronous'); callback() }; async.series([ function(callback) { somethingAsynchronous(function(err,result) { if(err) { callback(err); } else { callback(result); } }); }, function(callback) { somethingElseAsynchronous(function(err,result) { if(err) { callback(err); } else { callback(result); } }); ]);
To execute tasks in order and use the results of previous tasks, you have to use the waterfall method.
The last function specified will handle the result of the tasks executed. When an error occurs prior to executing all the specified tasks, then the other tasks will not execute and the last function will handle the error.
var somethingAsynchronous = function(callback) { callback(null,'This is a result'); }; var somethingElseAsynchronous = function(firstResult,callback) { callback(null,firstResult+" and this is appended"); }; async.waterfall([ function (callback){ somethingAsynchronous(callback); }, function(result,callback) { somethingElseAsynchronous(result,callback); } ], function(err,result) { console.log('The end result is: '+result); });
The method parallel is used to execute tasks in parallel and synchronize them after their execution.
var somethingAsynchronous = function(callback) { /* Asynchronous code */ callback(null,'23'); }; var somethingElseAsynchronous = function(callback) { /* Asynchronous code */ callback(null,'sad'); }; async.parallel([ somethingAsynchronous, somethingElseAsynchronous ],function(err,result){ console.log('The result is '+result); });
In case of an array of objects that need to be processed in an asynchronous manner then we can use map.
var items = ['a','b','c','d']; async.map(items,function(item,callback) { callback(null,'Did something asynchronous with '+item); }, function(err,results){ results.forEach(function(result) { console.log(result); }); });
Reference: | Async for Node.js from our WCG partner Emmanouil Gkatziouras at the gkatzioura blog. |