综合编程

Async & Await in Reactjs - Why use it?

微信扫一扫,分享到朋友圈

Async & Await in Reactjs - Why use it?
0 0

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).

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

  • 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.

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

Why use it?

ES7’s Async + Await allows the developer to write more concise asynchronous code.

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.

componentDidMount() {
	try {
	     getData()
	      .then(result => {
		const data = JSON.parse(result)
		this.setState({data)
		})
	    //  handle errors
	      .catch((err) => {
		 console.log(err)
	       })
	} 
         catch (err) {
		console.log(err)
	}
    }
}

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.

First wrap componentDidMount() with the async keyword:

async componentDidMount() {
    try {
    } catch (err) {
      console.log(err)
    }
  }
}

Create a variable that contains the await  syntax: 

componentDidMount() {
	try {
	  const res = await getData()
	} catch (err) {
		console.log(err)
	}
  }
}

If data is returned set our state with it else set the error message from the response.

componentDidMount() {
	try {
	 const res = await getData()
	 const data = res.data;
	 this.setState({ data })	
	} catch (err) {
		console.log(err)
		this.setState({ error: err.message })
	}
}
}

We’ve simplified the process here, remember that await, when returned,  is the equivalent to then() .

This piece of asynchronous code is more concise and async + await takes care of the data request behind the scenes.

Multiple Requests

What if I want two data requests, where one waits until the other is finished? Await can be used synchronously in this way:

componentDidMount() {
	try {
	 const resOne = await getData()
	 const resTwo = await getDatatwo()	
	} catch (err) {
		console.log(err)
		this.setState({ error: err.message })
	}
}
}

In the above example, resTwo will wait until  resOne finishes.

This promotes synchronous actions which might not necessarily be what we want. How can we ensure that both these calls are both completed at once?

Previously, with Promise.all() , an array of Promises are created and is returned when all are completed.

Promise.all(
 [
  actionOne(),
  actionTwo()
  actionThree()
 ]
)

This is actually more efficient then using 3 or 4 awaits in a row.

This is definitely something to be aware of when waiting for multiple data sets to be successfully retrieved in a larger Reactjs project.

However, if looking for a combination of await and Promise.all   the following exists:

let [foo, bar] = await Promise.all([getData(), getDataTwo()]);

For a deeper understanding of Promises I’d suggest reading Daniel Brain’s post.

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 .

Echo JS
感谢您的支持!

    What do you name color variables?

    上一篇

    Expedia sees Google as a continuing threat, but its CEO sets aside calls for regulating the...

    下一篇

    您也可能喜欢

    评论已经被关闭。

    插入图片

    热门分类