Async & Await in Reactjs – ES7 – Why use it?

Throughout all of my React projects, I find myself using Async & Await for every external data request. In this post, I want to highlight the general benefits of using this syntax while also demonstrating how I use it in Reactjs.

JavaScript Promises

Before we implement Async + Await, it is important to identify which problem it solves. To do this we must understand Promises.

One of the most important concepts for a JavaScript developer to understand is that of a Promise

A Promise in JavaScript is used to execute and manage asynchronous operations. It is an alternative to traditional callback-based approaches.

A simple example of a Promise:

fetch(url)
  .then((res) => filterData(res))
  .then(saveData())
  .catch(displayError)
;

A small chain of actions occurs here. We want to filter and save the data once it has been fetched.

This sequence is called a Promise because its promising to return data, but doesn’t specify when. Since we don’t have an exact return time, we might want to execute other code in the meantime.

Once it has returned the code in .then() executes. With (res) => representing the response of the Promise. This situation describes an asynchronous code set-up.

Asynchronous vs Synchronous

The opposite of a asynchronous action is a synchronous one. But what is the difference between a synchronous and a asynchronous action?

Well, a simple differentiation might look like this:

  • Synchronous code
    • Expects code to run in sequence.
    • When executing a function, wait for function to finish before running the next line.

A simple example of code that would be run sequentially in JavaScript:

console.log('Hi');
console.log('Welcome');
console.log('Goodbye');

This makes perfect sense – we read from top to bottom so we would naturally expect code to run in a similar sequential order. And that is exactly how synchronous code runs.

In fact, JavaScript is a single threaded synchronous language.  It interprets the code we’ve written line-by-line. However, we can still manipulate it to behave in an asynchronous way (i.e not sequential).

  • Asynchronous code
    • Avoids running in sequence bottleneck
    • When executing a function, don’t wait for it to finish before running the next line.

Asynchronous code does not want to wait for one thing to finish.

When a blocking operation is needed (e.g HTTP request), the request is started, and the code keeps running without blocking for the result. 

When the response is ready, the code will stop what its doing and revert back to the code that was intended to run once the request was finished.

Once the basic concept of these two types of actions is understood, the benefits of Async + Await becomes more clear.

For more information about JavaScript as a single threaded language watch the video below: