Saturday, December 1, 2018

Promise() and Async Await in React


What is Promise?

In general world, when we talk about promise, it is some event which is happening in future.
We just keep a tab somewhere in our mind about that promise, and keep doing our regular work. Once that promise is fulfilled, we get rewards or result of that promise.

e.g. My father promised me and my sister, if we get more than 90 marks in maths, He will buy me a carom board and pink bicycle to her.

Promise din’t stop our daily routine or work, when our result was out and as she scored 98, she got bicycle (promise resolved) and I got 67 marks, I got nothing (promise rejected).

Similarly in JavaScript promise is something which is not going to happen immediately, so program is continuously doing other things, and once promise is resolved or rejected, take the action accordingly.

function reward(marks) {
               return new Promise((resolve, reject) => {
                              if (marks > 90) {
                                             resolve({data: ‘you will get reward as promised’})
                              } else {
                                             reject({data: ‘no gifts’})
                              }
});
}

function isRewarded(marks) {
               this.reward(marks).then ((response) => {
                              console.log(response.data)
               }).catch((error) => {
                              Console.log(error.data)
               });
}
render() {
               this.isRewarded(this.props.marks);
   console.log(‘We are eating our breakfast’);
   console.log(‘We are getting ready for school’);
}

If isRewarded() is run against my marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’
‘no gifts’

If isRewarded() is run against my sister marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’
‘you will get reward as promised’


New JavaScript standards simplified it further, no need to write then() just use await and async.
1.      Make function async which has to wait for the promise in our case it is isRewarded function.
2.      Put await in front of the function call, which is returning promise.
3.      Done.

Above code with async await will be:

function reward(marks) {
               return new Promise((resolve, reject) => {
                              if (marks > 90) {
                                             resolve({data: ‘you will get reward as promised’})
                              } else {
                                             reject({data: ‘no gifts’})
                              }
});
}

async function isRewarded(marks) {
               let response = await this.reward(marks)
               console.log(response.data);
}

render() {
               this.isRewarded(this.props.marks);
console.log(‘We are eating our breakfast’);
console.log(‘We are getting ready for school’);
}

If isRewarded() is run against my marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’

If isRewarded() is run against my sister marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’
‘you will get reward as promised’

Did you observe anything ???

For run against my marks nothing printed as part of promise.
The only reason is await async only takes care of positive flow i.e. only resolve() not the reject().
We have to explicitly handle reject() and the simple solution is to put await function call inside try-catch block:

Make below changes and output for my marks will start coming:

async function isRewarded(marks) {
               try {
                              let response = await this.reward(marks)
                              console.log(response.data);
               } catch (error) {
                              console.log(error.data);
               }
}


Hope it helps....

No comments: