Understanding Async/Await in Javascript

Benefits of restructuring Promises with async and await

Understanding Async/Await in Javascript

Promises in Javascript

A promise is commonly defined as a proxy for a value that will eventually become available.

In layman terms, a promise in Javascript is very much similar to a promise in real life. A promise is like a commitment which will either be fulfilled/resolved or rejected. Promises are designed to handle asynchronous code without encountering a callback hell.

Once a promise has been called, it will start in a pending state. This means that the calling function continues executing, while the promise is pending until it resolves, giving the calling function whatever data was being requested.

The created promise will eventually end in a resolved state, or in a rejected state, calling the respective callback functions (passed to then and catch) upon finishing.

Async/Await in Javascript

An async function is nothing different or new but a mere change in handling the promises. Async/Await is just a sugar coated way of writing promises.

When using chaining in promises, though it was somewhat better than callbacks it still might get messy when managing huge chunks of code. With async/await the chaining using .then() and .catch() is totally eliminated.

First let's recap on how the usual promises are written.

The Usual Promise

fetch("https://dummy.api");
.then(response => response.json());
.then(console.log);
.catch(err => console.log(err))

Promises in Javascript are written with the help of chaining.

.then() tells what to do if the promise is fulfilled

.catch() tells what to do if the promise is rejected

.finally() tells what to do irrespective of the promise being fulfilled or rejected

It can be seen in the above code snippet that if the promise (i.e. fetching data from the url) is fulfilled, then convert the response to json and then the converted response is logged on the console. But, if the promise gets rejected and returns with an error then the error is printed on the console as can be seen in the .catch() code.

Restructuring the Promise with async and await

const getData = async () => {
   try{
      const response = await fetch("https://dummy.api");
      const data = response.json();
      console.log(data);
     }catch(err){
      console.log(err);
     }
}

With the usage of async/await in the function, one can get rid of the chaining part of the promises. This happens because of the two keywords async and await.

Async Keyword

The async keyword when put in front of a function declaration turns the function into an asynchronous function. An asynchronous function knows to expect the possibility of the await keyword being used to invoke asynchronous code. The beauty of this usage lies in the fact that invoking an async function always returns a Promise i.e. their return values are guaranteed to be converted to Promises.

Await Keyword

The usage of async becomes advantageous only when it is combined with the keyword await. In Javascript, await only works inside an async function, and when written in front of the promise-based function, it pauses the code and waits till the promise is executed and returns with a value.

Depending upon the status of the promise whether it is fulfilled or rejected, the next code is executed. If the promise is fulfilled, then the following lines of code would be executed and if the promise is rejected, then the lines in the catch block would be executed.

Benefits of using async and await

Better Error Handling

Using async/await allows us to handle the synchronous code and asynchronous code in the same manner. If there's an error in resolving the promise, then the control will jump directly to the catch block to handle the error. Multiple promises can also be written in the same try block, and the code will catch the errors for all the promises, not just one. It also tells you where the error occurred, and in which promise.

Better Code

async and await allows us to write clear and more understandable code by making it look more like synchronous code. It can be seen clearly how much cleaner the code has become. Moreover, when the code has conditional codes aswell, one can easily think of how much benefit can be gained by using the async/await way of writting promises than the usual way

Keypoints

  • Adding async to a function means you’ll always return a promise

  • Using async also enables the use of the await keyword, which allows you to wait until a promise is resolved

  • Using the await keyword blocks the code from executing until the promise is resolved or rejected. If the promise cannot settle, it generates an exception which can be dealt with

  • Usage of async/await makes the code more explicit, easier to understand, and more concise

Hope you understood the concept of Async and Await

Thank you for reading : -)