Overview (Loop Mode - Common)
Declare array and asynchronous method to iterateDeclare an array: ⬇️ const skills = ['js', 'vue', 'node', 'react'] Declare another promise asynchronous code: ⬇️ function getSkillPromise (value) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(value) }, 1000) }) } Use in for loopSince the for loop is not a function, and async and await need to be used in functions, we need to wrap a layer of function inside the for loop. async function test () { for (let i = 0; i < skills.length; i++) { const skill = skills[i] const res = await getSkillPromise(skill) console.log(res) } } test() // call When using await, you want JavaScript to pause execution until the awaited promise returns a result. The above result means that if there is asynchronous code in the for loop, you can wait until the asynchronous code in the for loop is completely run before executing the code after the for loop. But it cannot handle callback loops, such as forEach, map, filter, etc. The following is a detailed analysis. Use in mapWhen using await in map, the return value of map is always a promise array, because asynchronous functions always return promises. 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 array of promises start [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ] end If you want to wait until the promise is fulfilled, you can use promise.all() to handle 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() // Result start [ 'js', 'vue', 'node', 'react' ] end Use in forEachFirst, the code and results async function test () { console.log('start') skills.forEach(async item => { const res = await getSkillPromise(item) console.log(res) }) console.log('end') } test() Expected Results
The actual result is that console.log('end') is executed before the forEach loop waits for the asynchronous result to be returned.
forEach in JavaScript does not support promise awareness, nor does it support async and await, so you cannot use await in forEach. Use in filterUse filter to filter item as vue or react option Use filter normally: async function test () { console.log('start') const res = skills.filter(item => { return ['vue', 'react'].includes(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'].includes(item) }) console.log(res) console.log('end') } test() Expected results:
Actual Result:
Conclusion: Because the promise returned by the asynchronous function getSkillPromise is always true, all options pass the filter. Attached with usage summary
Conclusion: Due to the large form extraction component encountered in the work, asynchronous verification encountered this problem. Later, after consulting the data, the result was summarized SummarizeThis is the end of this article about the correct use of async and await in JS loops. For more relevant content about the use of async and await in JS loops, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Basic learning tutorial of table tag in HTML
>>: Introduction to user management under Linux system
To put it simply, website construction is about &q...
The effect to be achieved is: fixed zoom in twice...
Table of contents Preface 1. Preparation 2. Actua...
Take the deployment of https://gitee.com/tengge1/...
Nginx supports three ways to configure virtual ho...
usemap is an attribute of the <img> tag, use...
Table of contents Preface Several common bit oper...
This article uses examples to illustrate the prin...
Requirements: Remove HTTP response headers in IIS...
The previous article has installed the docker ser...
Solution to MySql service disappearance for unkno...
Recently, I have been working on thesis proposals ...
LocalStorage stores Boolean values Today, when I ...
Table of contents Preface Case optimization summa...
Preface After this blog post was published, some ...