Promise in nodeJS

NodeJS is an asynchronous , single threaded architecture. It is non blocking. To solve the asynchronous execution in synchronous way, we should have to use either callback function or promise.

Using promise in nodeJS : Promise are the design construct that are introduced to handle the complexity of asynchronous programming in javascript.If a method returns the promise then it can be handled by either resolve or reject methods.

var doctors = [
{id : 1,name : 'Mohan kumar',spe : 'ENT'},
{id : 2,name : 'Sohan kumar',spe : 'CARDIO'},
{id : 3,name : 'Rohan kumar',spe : 'NEURO'}
];
var findDoctor = function(id){
return new Promise(function(resolve,reject){
vardoctor=doctors.find(function(doc){
returndoc.id==id;
})
if(doctor){
resolve(doctor)
}
else{
reject('No record found')
}
})
}

Note : ES6 introduced few new Array methods. They are :

i)find() : It returns the first match

ii)findIndex() : It returns the index of first match

Now let us go more inside the code :

Create one more new array with name ratings. 

var ratings = [
{
id :1,
doctorId :1,
rating :10
},
{
id :2,
doctorId :1,
rating :9
},
{
id :3,
doctorId :2,
rating :8
}
]

 

Now let us create a function that will return the different rating assigned to the doctor in the form of array. For example the doctor with id 1 have following ratings
{
id :1,
doctorId :1,
rating :10
},
{
id :2,
doctorId :1,
rating :9
}
var findRating = function(docId){
return new Promise(function(resolve,reject){
var ratingsArr = ratings.filter(function(rateObj){//filter return array of objects having matching
return rateObj.doctorId == docId;
})
resolve(ratingsArr)
})
}

At last let us use the promise chaining for both methods ie : findDoctor() and findRating()

var findAvg = function(){
return findDoctor(1).then(function(docObj){

return findRating(docObj.id);

})
.then(function(ratings){

var rings=ratings.map(function(rateObj){

return rateObj.rating;
})

var finalAns=rings.reduce(function(T,e){
return (T+e);
})
return (finalAns/ratings.length);
})
}

 

 Now calling the function findAvg:

output :

➜ async-await node app3.js
Final response is 9.5

The above code contains a lot of hectics and of course promise chaining. To resolve this problem we will use , async operator. async always return a promise. Let us do one example

var findUser = async(function(){

return 'Mohan';

})

The above example is same as below code :

var findUser = function(resolve,reject){

resolve('Mohan');

}

 

So, whatever we will return inside the async , it will going to be resolved finally
If we want to call the above method defined with async. The async method will always return promise.So, to capture it we can use then and catch block
findUser().then(function(res){
console.log('The response is ',res);
})
.catch(function(er){
console.log('The error is ',er);
});

How to handle error in async feature

We know that whatever we return from the async will surely be resolved. If any error comes then we can handle is differently

throw new Error(‘Some error comes’)

Now, then method waits for the response from the server. So, again we have await method that is used along with the async feature. We will use await just before the promise. Just waiting for the response from the promise.
Now let us paste the older code and implement it into the new code
var findAvg = function(){
return findDoctor(1).then(function(docObj){
return findRating(docObj.id);
}) .then(function(ratings){
var rings=ratings.map(function(rateObj){
return rateObj.rating;
})
var finalAns=rings.reduce(function(T,e){ return (T+e); }) return (finalAns/ratings.length);
}) }

new One

findAltAvg = async function(){
var docObj = await findDoctor(1);
var ratings = await findRating(docObj.id)
var rings = ratings.map(function(rateObj){
return rateObj.rating;
})
Now call the function : 
findAltAvg(1).then(function(res){
console.log('Final response is ',res)
})
.catch(function(er){
console.log('The error is ',er)
})

In above programme , await is same as the then() method.

var docObj = await findDoctor(1); // await will wait for the findDoctor(1) to return complete response to docObj

By Pankaj Kumar Agarwal

Leave a reply:

Site Footer