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 } ]
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); }) }
findAvg(1).then(function(res){ console.log('Final response is ',res) }) .catch(function(er){ console.log('The error is ',er) })
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'); }
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’)
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