Home Web Front-end JS Tutorial How to optimize js async function

How to optimize js async function

May 30, 2018 am 10:16 AM
async javascript optimization

This time I will show you how to optimize the js async function and what are the precautions for optimizing the js async function. The following is a practical case, let's take a look.

First of all, you need to understand Promise

Promise is the basis for using async/await, so you must first understand what Promise does

Promise is a good thing to help solve callback hell and make asynchronous processes clearer.

A simple example of converting Error-first-callback to Promise:

const fs = require('fs')
function readFile (fileName) {
 return new Promise((resolve, reject) => {
  fs.readFile(fileName, (err, data) => {
   if (err) reject(err)
   resolve(data)
  })
 })
}
readFile('test.log').then(data => {
 console.log('get data')
}, err => {
 console.error(err)
})
Copy after login
We call the function to return a Promise instance, and read the file during the instantiation process. When the file The read callback is triggered to change the Promise state. We use then to monitor changes in the resolved or rejected state. The first callback is for resolve processing, and the second callback is for reject processing.

The relationship between async and Promise

The async function is equivalent to a shorthand function that returns a Promise instance. The effect is as follows:

function getNumber () {
 return new Promise((resolve, reject) => {
  resolve(1)
 })
}
// =>
async function getNumber () {
 return 1
}
Copy after login
Both are used in exactly the same way. You can use then to monitor the return value after calling the getNumber function. And how to use the await syntax corresponding to async: The execution of

getNumber().then(data => {
 // got data
})
// =>
let data = await getNumber()
Copy after login
await will get the Promise execution result behind the

expression, which is equivalent to us calling then to get the callback result. P.S. When async/await support was not very high, everyone would choose to use generator/yield combined with some libraries similar to co to achieve similar effects

Async function code execution is synchronous, and the result is returned It is asynchronous.

The async function always returns a Promise instance. This is very important. So when calling an async function, it can be understood that the code inside is in new Promise, so it is executed synchronously. The final return operation is equivalent to calling resolve in the Promise:

async function getNumber () {
 console.log('call getNumber()')
 return 1
}
getNumber().then(_ => console.log('resolved'))
console.log('done')
// 输出顺序:
// call getNumber()
// done
// resolved
Copy after login

The Promise inside the Promise will be digested

That is to say , if we have the following code:

function getNumber () {
 return new Promise(resolve => {
  resolve(Promise.resolve(1))
 })
}
getNumber().then(data => console.log(data)) // 1
Copy after login
If we follow what is said above, the data we get in then should be the value passed into resolve, which is another Promise instance.

But in fact, we will get the return value directly: 1. That is to say, if a Promise is returned in Promise, the program will actually help us execute this Promise and trigger then when the internal Promise state changes. callback.
An interesting thing:

function getNumber () {
 return new Promise(resolve => {
  resolve(Promise.reject(new Error('Test')))
 })
}
getNumber().catch(err => console.error(err)) // Error: Test
Copy after login
If we pass in a reject in resolve, we can directly use catch to monitor it externally.

This method is often used to throw exceptions in async functions
How to throw exceptions in async functions:

Be sure not to forget the await key WordsIf you forget to add the await keyword, no error will be reported at the code level, but the return value we receive is a Promise

let number = getNumber()
console.log(number) // Promise
Copy after login

, so be sure to use it when using it. Remember that await keyword

let number = await getNumber()
console.log(number) // 1
Copy after login
Copy after login

Not all places need to add await

During the execution of the code, sometimes, not all asynchronous operations need to add await. For example, the following operation on files:

We assume that all APIs of fs have been converted to Promise versions by us

let number = await getNumber()
console.log(number) // 1
Copy after login
Copy after login

We open a file through await, and then write the file twice.

But note that we did not add the await keyword before the two file writing operations.

Because this is redundant, we only need to notify the API that I want to write a line of text into this file. The order will naturally be controlled by fs

Then we use await to close the file at the end.
Because if we have not completed the writing process above, the close callback will not be triggered.
In other words, the triggering of the callback means that the above two steps of write have been completed.

Merge multiple unrelated async function callsIf we now want to get a user's avatar and user details (and this They are two interfaces, although they rarely appear under normal circumstances)

async function getUser () {
 let avatar = await getAvatar()
 let userInfo = await getUserInfo()
 return {
  avatar,
  userInfo
 }
}
Copy after login

这样的代码就造成了一个问题,我们获取用户信息的接口并不依赖于头像接口的返回值。
 但是这样的代码却会在获取到头像以后才会去发送获取用户信息的请求。
 所以我们对这种代码可以这样处理:

async function getUser () {
 let [avatar, userInfo] = await Promise.all([getAvatar(), getUserInfo()])
 return {
  avatar,
  userInfo
 }
}
Copy after login

这样的修改就会让getAvatar与getUserInfo内部的代码同时执行,同时发送两个请求,在外层通过包一层Promise.all来确保两者都返回结果。

让相互没有依赖关系的异步函数同时执行

一些循环中的注意事项

forEach

当我们调用这样的代码时:

async function getUsersInfo () {
 [1, 2, 3].forEach(async uid => {
  console.log(await getUserInfo(uid))
 })
}
function getuserInfo (uid) {
 return new Promise(resolve => {
  setTimeout(_ => resolve(uid), 1000)
 })
}
await getUsersInfo()
Copy after login

这样的执行好像并没有什么问题,我们也会得到1、2、3三条log的输出,但是当我们在await getUsersInfo()下边再添加一条console.log('done')的话,就会发现:

 我们会先得到done,然后才是三条uid的log,也就是说,getUsersInfo返回结果时,其实内部Promise并没有执行完。
 这是因为forEach并不会关心回调函数的返回值是什么,它只是运行回调。

不要在普通的for、while循环中使用await

使用普通的for、while循环会导致程序变为串行:

for (let uid of [1, 2, 3]) {
 let result = await getUserInfo(uid)
}
Copy after login

这样的代码运行,会在拿到uid: 1的数据后才会去请求uid: 2的数据

--------------------------------------------------------------------------------

关于这两种问题的解决方案:

目前最优的就是将其替换为map结合着Promise.all来实现:

await Promise.all([1, 2, 3].map(async uid => await getUserInfo(uid)))
Copy after login
Copy after login

这样的代码实现会同时实例化三个Promise,并请求getUserInfo

P.S. 草案中有一个await*,可以省去Promise.all

await Promise.all([1, 2, 3].map(async uid => await getUserInfo(uid)))
Copy after login
Copy after login

P.S. 为什么在使用Generator+co时没有这个问题

在使用koa1.x的时候,我们直接写yield [].map是不会出现上述所说的串行问题的看过co源码的小伙伴应该都明白,里边有这么两个函数(删除了其余不相关的代码):

function toPromise(obj) {
 if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
 return obj;
}
function arrayToPromise(obj) {
 return Promise.all(obj.map(toPromise, this));
}
Copy after login

co是帮助我们添加了Promise.all的处理的(膜拜TJ大佬)。

总结

总结一下关于async函数编写的几个小提示:

1.使用return Promise.reject()在async函数中抛出异常
2.让相互之间没有依赖关系的异步函数同时执行
3.不要在循环的回调中/for、while循环中使用await,用map来代替它

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用垃圾回收器

怎样使用Nodejs内存治理

怎样使用vue的toast弹窗组件

The above is the detailed content of How to optimize js async function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

In-depth interpretation: Why is Laravel as slow as a snail? In-depth interpretation: Why is Laravel as slow as a snail? Mar 07, 2024 am 09:54 AM

Laravel is a popular PHP development framework, but it is sometimes criticized for being as slow as a snail. What exactly causes Laravel's unsatisfactory speed? This article will provide an in-depth explanation of the reasons why Laravel is as slow as a snail from multiple aspects, and combine it with specific code examples to help readers gain a deeper understanding of this problem. 1. ORM query performance issues In Laravel, ORM (Object Relational Mapping) is a very powerful feature that allows

Discussion on Golang's gc optimization strategy Discussion on Golang's gc optimization strategy Mar 06, 2024 pm 02:39 PM

Golang's garbage collection (GC) has always been a hot topic among developers. As a fast programming language, Golang's built-in garbage collector can manage memory very well, but as the size of the program increases, some performance problems sometimes occur. This article will explore Golang’s GC optimization strategies and provide some specific code examples. Garbage collection in Golang Golang's garbage collector is based on concurrent mark-sweep (concurrentmark-s

Laravel performance bottleneck revealed: optimization solution revealed! Laravel performance bottleneck revealed: optimization solution revealed! Mar 07, 2024 pm 01:30 PM

Laravel performance bottleneck revealed: optimization solution revealed! With the development of Internet technology, the performance optimization of websites and applications has become increasingly important. As a popular PHP framework, Laravel may face performance bottlenecks during the development process. This article will explore the performance problems that Laravel applications may encounter, and provide some optimization solutions and specific code examples so that developers can better solve these problems. 1. Database query optimization Database query is one of the common performance bottlenecks in Web applications. exist

How to optimize the startup items of WIN7 system How to optimize the startup items of WIN7 system Mar 26, 2024 pm 06:20 PM

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star

What are some ways to resolve inefficiencies in PHP functions? What are some ways to resolve inefficiencies in PHP functions? May 02, 2024 pm 01:48 PM

Five ways to optimize PHP function efficiency: avoid unnecessary copying of variables. Use references to avoid variable copying. Avoid repeated function calls. Inline simple functions. Optimizing loops using arrays.

Vivox100s parameter configuration revealed: How to optimize processor performance? Vivox100s parameter configuration revealed: How to optimize processor performance? Mar 24, 2024 am 10:27 AM

Vivox100s parameter configuration revealed: How to optimize processor performance? In today's era of rapid technological development, smartphones have become an indispensable part of our daily lives. As an important part of a smartphone, the performance optimization of the processor is directly related to the user experience of the mobile phone. As a high-profile smartphone, Vivox100s's parameter configuration has attracted much attention, especially the optimization of processor performance has attracted much attention from users. As the "brain" of the mobile phone, the processor directly affects the running speed of the mobile phone.

See all articles