未加星标

Async & Await in Reactjs - Why use it?

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2018 | 作者 红领巾 ] 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
Async & Await in Reactjs - Why use it?

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
Async & Await in Reactjs - Why use it?

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()]); Fo

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

分页:12
转载请注明
本文标题:Async & Await in Reactjs - Why use it?
本站链接:https://www.codesec.net/view/620830.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(12)