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);  //returned by resolve method
},function(err){
console.log("err");
console.log(err);    //returned by rejecet method
});


Thats it.Its quite easy.

So now if you want to perform some actions after you have got the result of asyncJobFunction,you can do that by writing one more then
as explained below.

var promiseData=asyncJobFunction(); 
promiseData.then(function(result){

console.log("Success");
console.log(result);  //returned by resolve method
return result; //its required otherwise next then will not get anything because next then will not understand resolve or reject.it will only take what you return
},function(err){
console.log("err");
console.log(err);    //returned by rejecet method
return err;
}).then(function(result){
console.log("One more Then");
console.log(result);//Either result or err.Both will come here as this then will not understand resolve or reject as explained above.
});

same way you can write for subsequent actions with then.


Please comment if you have any doubt.

Comments

Popular posts from this blog

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

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