You want to execute an async function inside a map()
call, to perform an operation on every element of the array, and get the results back.
您想在map()
调用中执行一个异步函数,对数组的每个元素执行一个操作,并返回结果。
How can you do so?
你该怎么做?
This is the correct syntax:
这是正确的语法:
const list = [1, 2, 3, 4, 5] //...an array filled with values
const functionWithPromise = item => { //a function that returns a promise
return Promise.resolve('ok')
}
const anAsyncFunction = async item => {
return functionWithPromise(item)
}
const getData = async () => {
return Promise.all(list.map(item => anAsyncFunction(item)))
}
getData().then(data => {
console.log(data)
})
The main thing to notice is the use of Promise.all()
, which resolves when all its promises are resolved.
需要注意的主要事情是Promise.all()
的使用,它在所有诺言都得到解决时即会解决。
list.map()
returns a list of promises, so in result
we’ll get the value when everything we ran is resolved.
list.map()
返回一个list.map()
列表,因此result
是当我们解决所有运行问题时,我们将获得该值。
Remember, we must wrap any code that calls await
in an async
function.
请记住,我们必须将调用await
所有代码包装在async
函数中。
See the promises article for more on promises, and the async/await guide.
有关诺言的更多信息,请参见诺言文章 ,以及async / await指南 。
翻译自: https://flaviocopes.com/javascript-async-await-array-map/