Sign in
Log inSign up
Asynchronous Javascript - Async/Await

Asynchronous Javascript - Async/Await

Prem Kantikar's photo
Prem Kantikar
·Jul 13, 2021·

3 min read

Introduction

To understand async/await first let's take a step back and discuss a bit how JavaScript works. As you might have been aware JavaScript runs your code synchronously, meaning that it can only run one piece of code at a time and it must wait for that code to be completed in order to move to the next line of code. This can lead to some problems.

When your JavaScript code is executed, synchronous code has the potential to block further execution until it has finished what it’s doing. In other words, long-running JavaScript functions can make the UI or server unresponsive(Render Blocking) until the function has returned. Obviously, this can result in a terrible user experience.

To solve this issue we have the ability to run asynchronous code in JavaScript with the help of Web APIs. 😀

In Asynchronous, the execution will never wait to complete, instead, it will execute all the events in a single go and multiple events will be in progress, hence making JavaScript non-blocking.

The fetch API allows you to run asynchronous code by returning a Promise.

A promise is an object which keeps track of whether the asynchronous event has happened already or not and determines what happens after the event has occurred. Instead of providing a callback, a promise has its own methods (resolved or rejected), which you call to tell the promise what will happen when it is successful or when it fails.

const getPosts=()⇒{
  fetch("jsonplaceholder.typicode.com/posts")
   .then(response ⇒ response.json())
   .then(data ⇒ console.log(data))
   .catch(err ⇒ console.log(err));
};

The code above is making a request to the API

On line 4 of the code, we are using fetch API to make an HTTP request and this will eventually return a promise. If the promise is successful we will proceed to the code in the first then() method (line 5) and later to the second then() method (line 6). At any given point if a promise is unsuccessful/rejected our code will go directly to the catch()

Now let's see what Async/Await is,

Async/Await is a new feature added to JavaScript in ES8 and it basically allows you to write asynchronous code in a synchronous way.

If you use the Async keyword before the function definition, you can then use await within the function. Await gives you the power to pause the function in a non-blocking way until the promise is resolved.

const getPosts= async()⇒{
   try{
     const response = fetch("[jsonplaceholder.typicode.com/posts](https:…");
     const parsedResponse ⇒ await response.json();
     console.log(parsedResponse);
   }catch(err){
     console.log(err));
   }
};

First, we should let the JavaScript interpreter know that this function will execute some asynchronous code. We do this by adding the async keyword before our function.

You must wrap your entire code within the async function code block in a try/catch statement to handle the errors in case the promise is rejected/unsuccessful

The first constant response contains the promise returned from our HTTP request, but for this, to work we must first add the await keyword in front of our fetch function. The await keyword has to be added when you are expecting a promise in return.

Now that we have our data stored in a constant we can use it however we like.

The biggest benefit of using async/await is that it makes code much more readable and maintainable. It makes the code feel it's streamlined and structured similarly as though it is synchronous.

Conclusion

  • The code is more readable than using a callback or a promise.
  • Async functions return promises by default.
  • Error handling is simpler.
  • Debugging is easier.

Thanks for reading this blog and I hope that now you have a better understanding of async/await and how to use it.

⚡ Happy Coding.