Back
Featured image of post Async Await

Async Await

Introducing Async/ Await. A better way to handle and write Promise

Async/Await is another way to write asynchronous code in much easier and cleaner way to read. In this article, you will learn how you can simplify and transform your your callback or Promise code into Async/Await way.

Before you start reading this article, please make sure you already have the basic knowledge of how Promise work in javascript. If you are not clear about Promise work. Please checkout my previous blog which talks about how to create a Promise function and work on it. Learn More

We will be using back the Previous code and transform them from Promise to Async/Await

Promise function

What we previously did was we uses .then to handle whatever inside the resolve state and .catch for whatever inside reject state. Let’s see how we can transform them into Async/ Await function.

Promise to Async Await
Copy the full code here

As we can see the .Then method is being replace to Await. In order to use await, we must include Async infront of our function, it can be any type function like callback, traditional function, arrow function and etc. As await method is always Resolve the promise, we need to wrap them up into a Try/Catch statement so that resolve code will be executed inside try statement while reject will be executed inside catch statement.

You might not notice how Async/Await can be so useful because the example above is only returning single Promise. What if there are nested Promise returning such as Fetch API which first return the Promise of response status, and inside that Promise it return another Promise for response data.

Async Await in Fetch API
Copy the full code here

Summary

There are few things we need to be aware when we use Async/ Await function

  • Must include Async keyword infront of the function
  • Await method is only use for Resolve state
  • Wrap the code inside Try/ Catch, resolve state in (Try) and reject state inside (Catch)
comments powered by Disqus