Sometimes, we want to use promise function inside JavaScript array map.
In this article, we’ll look at how to use promise function inside JavaScript array map.
How to use promise function inside JavaScript array map?
To use promise function inside JavaScript array map, we use the Promise.all
function.
For instance, we write
const mappedArray = await Promise.all(
array.map(async (p) => {
const i = await getPromise(p);
return i.item;
})
);
to call array.map
with an async function that returns a promise with i.item
as its resolve value.
map
returns an array of promises with their resolve values.
Then we use Promise.all
to run all the promises and get their resolve values with await
.
Conclusion
To use promise function inside JavaScript array map, we use the Promise.all
function.