Day 1 : Async module of nodejs

Hi Guys,

I am working on our public API in node. In that i am doing an http call to an external API to check whether pickup and destination locations are serviceable or not. The partners/third parties can send array of multiple orders and i need to make these two external calls with each order and then store the response (whether serviceable or not) in a variable msg. So the problem is it is doing calls for each orders but not sequentially since node does it parallel.

I found a node package which is used to handle multiple callbacks and can make them perform sequentially also. The module name is “async” . You can see the documentation on github async .It provides a lot of methods to handle callbacks and one of them is async.each() method.

Example :

// assuming openFiles is an array of file names and saveFile is a //function to save the modified contents of that file:  
async.each(openFiles, saveFile, function(err){   
// if any of the saves produced an error, err would equal that error });
// assuming openFiles is an array of file names async.each(openFiles, function(file, callback) {
// Perform operation on file here.
console.log('Processing file ' + file);
if( file.length > 32 ) {
console.log('This file name is too long');
callback('File name too long');
} else {
// Do work to process file here
console.log('File processed');
callback();
} }, function(err) {
//if any of the file processing produced an error, err
would be equal that error
if( err ) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('A file failed to process');
} else {
console.log('All files have been processed successfully');
}
});

So in above example we pass an array as first argument and a function as second argument which will be called on each item of array by iterating over each item and then we do asynchronous task and if everything is perfect then we call callback with no parameter or null and if any error occurred then we call callback with error, and finally third argument (a function) is there which is called after all the iteration. if there was any errors in any of the iteration then it will have an error argument and all other processing will be stopped and if not then it will contain result of all iteration.

Since async.each() does iterations parallel and i wanted it in sequential order , for that it has a method as async.eachSeries() which does iterations one after the other sequentially.

Conclusion:

Async module is an awesome module to handle multiple asynchronous calls/callbacks and it provides tons of methods to do anything you want with it. I would recommend you should definitely try it if you have never used.

So, that’s it for today and i will be writing alternate days or everyday(if possible) tech stuffs that i know/learn.

Let’s see what i write in my next article. Have a great day!