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
- callOne(() => {
- callTwo(() => {
- callThree(() => {
- })
- })
- })
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
- Promise.prototype.then()
and
- Promise.prototype.catch()
methods return promises, they can be chained.
- addNumber(a,b){
- return new Promise((resolve,reject)=>{
- if(a!="" && b!=""){
- const add = (a, b) => a + b;
- resolve(add(2, 2));
- }else{
- reject("Invalid input")
- }
- })
- }
- addNumber(1,2)
- .then((response)=>{ console.log(response); })
- .catch((err)=>{ console.log(err); })
3) Async/await: it's a new syntax in JS ES6 - the improved promise!
- async getAllData(){
- try{
- return await userMdl.getAll({});
- }catch(err) {
- console.log(err)
- }
- }
Categories: Java Script Tags: #ES6, #JavaScript,