Async.each in Node.JS

As NodeJS works with single thread, so most of processing is in async mode.

But sometimes we face situation where we need to iterate through items in sync manner.

For example.

ForEach in JS works in async .

So using npm module async we can handle things and make code to wait until we have finished some code processing in between.

Syntax are :

async.each(array, iterator, callback);

— Array, Function, (optional) Function
iterator(item, next) receives current item and a callback that will mark the item as done. next callback receives optional error, transformedItem arguments.
callback(error, transformedArray) optionally receives first error and transformed result Array.

var async = require('async');

var items = [1,2,4,6,8,9];

console.log('async.each Example ..\n');

// Here parsing through all items and you need to call function after processing of all items 
// at the end done function will call callback or return of everything above is processed
async.each(items, function(item,callback){
	// having some async function call
	}, function(err){ // Will execute only when above all calls are done

//In above things were done in parallel fashion but done is called when everything is done.

console.log('\nasync.eachSeries Example ..\n');

// In below things will be in series ie sync , one call only after another is finished and in this way things will be executed.

async.eachSeries(items, function(item,callback){


Reference :


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s