Menu

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

07 December 2018

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 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:

Why use it?

It is just a piece of syntactical sugar for a developer’s JavaScript. An added bit of coding utility if you will.

When implemented correctly, it can do the following:

Make code more readable

Better describe when a asynchronous action begins + ends

Reduce the amount of code used overall for asynchronous actions

Essentially, async + await describes the use of a JavaScript Promise in a neat, more refined way. It makes Promises easier to follow and enables the develop to specify what code should be invoked when a Promise has finished.

Showing the differences

It is important to remember that a Promise and Async + Await both still create synchronous code.

In a simple React application, I find the most common usage of async and await is in the component lifecycle hook componentDidMount()

In more complex projects, or perhaps an implementation with Redux (a state manager for React), these async requests usually take place in an external store where many calls are needed.

This is a basic implementation of a Promise in a react component. Notice we specify .then() , whatever is put inside here will on occur after the request for data has finished. In this case, we set the state of the component with the retrieved data.

Using .then() ensures asynchronicity. It doesn’t matter if the data is returned now or later, whenever it does return all the code in the .then() will be run.

In the meantime, JavaScript can do other things while the request is being made.

Now, how does this differ from Async + Await? Well, essentially it is the exact same thing, just with a reduced amount of code written. And an easier way to understand when reading it.

Conclusion

Fundamentally, async + await is no different from Promises. But rather, it is a different way of writing them. We can’t get away from the fact that a deep understanding of Promises is still required when debugging code like this.

However, I find that it’s descriptive use of the words async and await enable the developer to write Promise based callback in a more understandable way.

Specifically, in my React projects, it has helped clean up all code that makes external request to retrieve data. And perhaps most importantly, any developer that might look at this code in the future will have a much better breakdown of which requests are asynchronous vs synchronous .