Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of correctly using async and await in JS loop

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What is the method of correctly using async and await in the JS cycle? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

At-a-glance (cycle-commonly used)

For

Map

ForEach

Filter

Declare arrays and asynchronous methods for traversal

Declare an array: ⬇️

Const skills = ['js',' vue', 'node',' react']

Declare another asynchronous code for promise: ⬇️

Function getSkillPromise (value) {return new Promise ((resolve, reject) = > {setTimeout () = > {resolve (value)}, 1000)} is used in the for loop

Because the for loop is not a function, and async and await need to be used in the function, it is necessary to coat the for loop with function.

Async function test () {for (let I = 0; I)

< skills.length; i++) { const skill = skills[i] const res = await getSkillPromise(skill) console.log(res) }}test() // 调用

When using await, you want JavaScript to pause execution until you wait for promise to return the processing result. The above results mean that there is asynchronous code in the for loop, and it is possible to wait until the asynchronous code in the for loop has completely run before executing the code behind the for loop.

However, he cannot handle callback loops, such as forEach, map, filter, etc., which are analyzed in detail below.

Used in map

With await in map, the return value of map begins with an array of promise, because asynchronous functions always return promise.

Async function test () {console.log ('start') const res = skills.map (async item = > {return await getSkillPromise (item)}) console.log (res) console.log (' end')} test ()

Result: always an promise array

Start [Promise {}, Promise {}] end

If you want to wait for the return result of promise, you can use promise.all () to deal with it.

Async function test () {console.log ('start') const res = skills.map (async item = > {return await getSkillPromise (item)}) const resPromise = await Promise.all (res) console.log (resPromise) console.log (' end')} test () / / used in the result start ['js',' vue', 'node',' react'] endforEach

Code and result first

Async function test () {console.log ('start') skills.forEach (async item = > {const res = await getSkillPromise (item) console.log (res)}) console.log (' end')} test ()

Expected result

'Start'

'js'

'vue'

'node'

'react'

'End'

The actual result executes console.log ('end') before the forEach loop waits for the asynchronous result to return

'Start'

'End'

'js'

'vue'

'node'

'react'

ForEach in JavaScript does not support promise awareness, as well as async and await, so you cannot use await in forEach.

Used in filter

Use filter to filter options where item is vue or react

Normal use of filter:

Async function test () {console.log ('start') const res = skills.filter (item = > {return [' vue', 'react']. Steps (item)}) console.log (res) console.log (' end')} test () / call / / result start ['vue',' react'] end

After using await:

Async function test () {console.log ('start') const res = skills.filter (async item = > {const skill = await getSkillPromise (item) return [' vue', 'react']. Steps (item)}) console.log (res) console.log (' end')} test ()

Expected results:

Start

['vue',' react']

End

Actual results:

['js',' vue', 'node',' react']

End

Conclusion: because the promise returned by the result returned by the asynchronous function getSkillPromise is always true, all options are filtered

If you want to execute await calls continuously, use a for loop (or any loop without a callback).

Never use await with forEach, but use a for loop (or any loop without a callback).

Do not use await in filter and reduce, if necessary, use map for further processing, and then use filter and reduce for processing.

The answer to the question about how to correctly use async and await in the JS cycle is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report