Categories
JavaScript Answers

How to use promise function inside JavaScript array map?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *