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.
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.
list.map()
returns a list of promises, so in result
we’ll get the value when everything we ran is resolved.
Remember, we must wrap any code that calls await
in an async
function.
See the promises article for more on promises, and the async/await guide.
Download my free JavaScript Beginner's Handbook and check out my JavaScript Course!
More js tutorials:
- JavaScript Loops
- JavaScript Data Structures: Set
- The definitive guide to JavaScript Dates
- JavaScript Function Parameters
- JavaScript Asynchronous Programming and Callbacks
- This decade in JavaScript
- What's the difference between using let and var in JavaScript?
- The JavaScript filter() Function
- How to wait for 2 or more promises to resolve in JavaScript