How to handle response from asynchronous call.?

How to handle response from asynchronous call.?
----------------------------------------------

To handle the asynchronous response in javascript we can use three methods like Callback, Promise, Async/await: it's a new syntax in JS ES6 - the improved promise!

Let's take a look at each one of them.

1.Callback

  1. callOne(() => {  
  2.   callTwo(() => {  
  3.     callThree(() => {  
  4.     })  
  5.   })  
  6. })  

Callback basically means passing response from one to another function as a chain. That other function can call the function passed whenever it is ready. In the asynchronous process, callbacks are called when an asynchronous process is done which means the response is passed to the callback.

2.Promise

Promises are used to handle asynchronous operations in JavaScript.

A Promise can be in on of these states:

  • fulfilled - The action relating to the promise succeeded
  • rejected - The action relating to the promise failed
  • pending - Hasn't fulfilled or rejected yet
  • settled - Has fulfilled or rejected

when promise occurs its response can be fulfilled in two ways 
As the

  1. Promise.prototype.then()  

and

 

  1. Promise.prototype.catch()  

methods return promises, they can be chained.


  1. addNumber(a,b){  
  2.     return new Promise((resolve,reject)=>{  
  3.   
  4.       if(a!="" && b!=""){  
  5.         const add = (a, b) => a + b;  
  6.         resolve(add(2, 2));  
  7.       }else{  
  8.         reject("Invalid input")  
  9.       }  
  10.   
  11.     })  
  12.   }  
  13.   
  14. addNumber(1,2)  
  15.       .then((response)=>{ console.log(response); })  
  16.       .catch((err)=>{ console.log(err); })  

3) Async/await: it's a new syntax in JS ES6 - the improved promise!


  1. async getAllData(){  
  2.         try{  
  3.             return await userMdl.getAll({});  
  4.         }catch(err) {  
  5.             console.log(err)  
  6.       }  
  7.     }  

 

 

Categories: Java Script Tags: #ES6, #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.