Best Way To Implement async.auto for dependent tasks in nodejs

Posted By : Praddumn Kumar | 10-Apr-2017

async.auto() is a function offered by the libary which allows you to declare a set of tasks and their dependencies, then the library determines the best way to compose the initialization.

The first parameter of the function is an object of tasks. They follow the format taskName: function or taskName: [dependencies, function].

In async.auto tasks with dependencies will only start when those(dependent task) have been resolved.

So async.auto is used when we have some function that need to be executed in certain order .

 

Let's take a example of signup to understand the async.auto from example ,in we will check that user exist in db or not .

 

var async = require(async);
async.auto({ get_username:function(callback)
{
console.log(“ in get username “);
//code to get some data......
callback(null,”username”); },
connnect_to_db:{
console.log(“in connnect to db”);
var connected = true; //code to get some data......
//check connection
if(connected)
{ callback(null,connected);
}else{
callback(err,”error while connecting to db”);
} },
check_if_user_exist:['get_username','connect_to_db', function(callback,results)
{
console.log('in check if user exist ', JSON stringify(results));
// check if user exist in db......
var userExist = false; if(userExist){
callback(“ user already exist in db”);
}else{
callback (“user does not exist in db “) } }] )} 

 

var async = require(async);

 

Async is a module which provides powerful functions for working with asynchronous features of javasctipt.

Although initially it was designed for use with Node.js . We can install it through npm install –save async.

In the above example there are three functions get_username ,connnect_to_db ,check_if_user_exist.

First function takes the name of user and second function is used to make connection with the database , third function is dependent on result of first and sectond function so after completion of first and second function third function will be executed .

THANKS

 

About Author

Author Image
Praddumn Kumar

Praddumn is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..