Async / Await Vs Promises

A

In this blog, we are learning about the concepts of javascript that handle asynchronous operations. This includes promises & async / await to handle operations. we will learn how we can use it or Part from that what is the difference between them? while writing code, let’s go we will find out.

Promises:-

A promise in javascript is similar to a promise in real life. it’s the same as if we made some promise to our friend to take him to the restaurant. so at the Initial state Promise is pending. there are only two things that happen if a promise is fulfilled means you take your friend to the restaurant or else rejected means you tell him that we may go on some other day same in promises

  • Pending:- Initial State, before the event has happened.
  • Resolved:- After the operation is completed successfully.
  • Rejected:- If the operation had an error during execution, the promise fails.
  • It has these 3 States Pending, resolved & rejected.
  • Error Handling is done by using then() & catch() methods
  • This block of code is difficult to understand sometimes

Example:-

Considering we are fetching data from API, Promise is in a pending state until data is fetched. If data is received successfully then the promise is in resolved state else if data is not received or the API call fails then the promise is in the rejected state.

Async / Await:-

Async / Await is used to work with promises in asynchronous functions. It will wrap the code to make promises easier to read & use.

  • It will return a promise whether it is resolved or rejected, it does not have a state.
  • Error handling using try() & catch () method.
  • using async / await makes code more readable.
Async:-
  • The async function always returns us a promise
  • The Async function comes in ES 2017
  • It will work as an asynchronous behavior.
Await:-
  • We can use await function only inside the async function.
  • It will wait till the process gets completed. 
Example:-

we use try block to resolve promises & catch to handle the rejected promises to run code we use the final methodĀ 

In this blog, we learn about Promises & Async / Await. Hopes you like this blog and that it’s helpful to you. Thanks for reading this Blog.

About the author

Khilesh Sarode
By Khilesh Sarode

Category