Promise method of Node JS and how it simplifies the callback problem

Hi guys,Today we will see how  we can avoid callback problems by Advanced method of node Provided by Node version 6.5.0 (or further version). Its Promise method.You don't need to include any library for that.Below  is the example. function asyncJobFunction() { var url="mydomain.com"; return new Promise(function(resolve,reject){ //Write here your Async Code call.Get(url,function(err,data) { if(err) { reject(err); ///Reject the Promise by calling the reject method. } else { console.log("Success"); resolve(data); ///Resolve the Promise by calling the resolve method. } }) }) } above we have written one function asyncJobFunction which returns the promise object.so we have to catch the result either resolve or reject. lets see how we can catch that. var promiseData=asyncJobFunction();  promiseData.then(function(result){ console.log("Success"); console.log(result);  /...

Introduction to Node JS and How to Overcome Callback Problems in it

Introduction:- 

As you all know,Node.js is a server side platform built on Google Chrome's Javascript Engine(V8 Engine).It provides a rich library of various JavaScript modules which simplifies the web development to great extent.

Node js runs asynchronously with single thread that's why its faster compare to others.
But Sometimes it can make you worry a little because If you have worked on java or other technologies which executes synchoronously,there you dont need to worry about how two functions will execute because those were running synchronously.It can wait one after another.


In Node JS,its not the same case.Second function will execute before first function if first function will take time.let me explain you by simple example.

var x=0;
for (var i=0;i<50;i++)
{
  x=x+1;
}
xyz(x); //Calling function xyz
console.log("Hello World");
function xyz(x)
{
   //Time consuming code
}


In above case,It will first print Hello World before giving output of xyz function if your function xyz
is containing some time consuming code like 

mongodb.connection("localhost:27017",function(err,db)
{
   if(err) throw error
 
  else
 {
   console.log(db);
  }

 
});


Because this function will wait for connection to be established and will give result as err or db.So Node can not wait for that and time so it will execute next statement console.log("Hello World"); and then output of that function will come.

If you function xyz()  is containing normal code like
function xyz()
{
  for (var i=0;i<50;i++)
 {
    x=x+1;
 }
 console.log(x);
}

 then Its not a problem so first it will print x value and then it will print Hello World.



So your question would be how to overcome with this Asynchronous execution problem.
Its called CallBack Hell Problem in Node JS.Every Node Developer should be able to overcome that problem.

Here Below are the different ways you can use for dealing with it.

1)Simple way is use CallBack Method :-


function xyz(parameter1,callback)         //define function   
{
       if( dealwith(parameter1))
       {
            callback(null,"yes its successful");
       }
      else
      {
           callback("Its error",null);
       }
        

}

xyz(parameter1,function(err,data){            //call function
      if(err) throw error
      else
      {
            console.log(data);
      }


})    

This is a simple callback method mechanism for calling any function when you know it can sometime.so you can write code to be executed after function completion in else section of function call.


2)Second method is Modernization:-


var x1=function xy1(url)
{
},x2=function xy2()
{
x1=x1+1;
},
x3=function xy3()
{
x2=x2+1;
};

This is the simple mechanism used when all your functions are dependent on each other.in this case first function xy1 will execute .after it finishes,it will execute xy2 and after it ,it will execute xy3. 


3)Third method is Async Library:-


async is module.you can use it in your code by importing with simple statement as written below:-

var async=require('async');

async.waterfall:-


async.waterfall([function1,function2],function(err,data)
{
if(err)
{
}
else
{
  console.log("Its done");
}
}) 

In this case ,each function in array  passes the output to next function.All function will run one by one.if one function throws error,entire fall will be broken and stop executing functions and will go to err section.

async.series:-

async.series([function1,fuunction2],function(err,data)
{
console.log("Its done");
})
In this case ,data contains the consolidated output of all functions.This is the same like above async.waterfall.The only difference is output given to final data.


async.parallel:- for parallel execution of multiple functions and merging result of all at end:-

execute the below code to understand how the parallel execution of multiple functions together happens
****************************************************************************************
var async = require('async');
var one,two,three;
var count=0;
async.parallel({
    one: function(callback) {
      console.log("One");
      one=1;
  count=count+1;
  callback(true, "one output");
    },
    two: function(callback) {
      console.log("Two");
  two=2;
  count=count+1;
//sconsole.log(count);   
  callback(null,"two output");
},
    three: function(callback) {
      console.log("Three");
      three=3;
  count=count+1;
  callback(null,"three output");
    }
  }, function(err, results) {
    // results is now equals to: {one: 1, two: 2}
if(err)
{
console.log("error here");
console.log(count);
console.log(err);
}
else
{
console.log("ddata here");
//console.log(count);
console.log(results);
}
    
  });
*********************************************************************************async.parallel is used when there is scenarion of executing multiple functions in parallel and want to merge output of all at end , we can use it. as shown above,if even one function gives error,it will go to err section but all other function will execute too.
Also you have to return callback from every function so that it can know that whether function is executed successfully or not.


4) Fourth method is Promise:-


var x=require('promise');

var y=funct1(url);

.then(function(err,db)
{
if(err)
else
{
console.log(db);
}
})

.catch(err)
   console.log(err);
}


Promise is one of the good method used for callback hell problem.When you use promise method,your code will look good from reader point.
You just have to import module 'promise' then you can call function like shown above.
after that you can use .then() for catching successful data and .catch for catching errors.
even you can use  .then() anywhere where you can think it should wait for statements defined before to be executed.


5) Fifth method is Putting Timer:-


You can put timer like SetTimeout(func,3000) for blocking the Execution of Node Code.But its not advisable in real projects.

So above are the methods you can use as per your required scenarios.
Also there are some predefined modules in node which you can use at server side be default without importing it.
For ex:- Buffer.It can specially used when your data is in millions and you want queue mechanism for step by step execution.


Explore node.js.It is very powerful server side scripting.you can also implement multi thread environment in Node with Creating Child process in Single Thread Environment.You can find different modules for that and use it with simple var a=require('module_name'); statement.

Its so much simple right!!!! 


Please comment if you have any doubt.I will try to comment as early as possible.









Comments

Popular posts from this blog

File Upload and Send it Through AJAX to node.js Server in SAPUI5 Application

Promise method of Node JS and how it simplifies the callback problem