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 method.

For instance, we write

const mappedArray = await Promise.all(
  array.map((p) => {
    return getPromise(p).then((i) => i.Item);
  })
);

to call Promise.all with an array of promises returned by map to invoke all the promises in the returned array in parallel.

And we use await to get an array all the results from the promises in the array.

Conclusion

To use promise function inside JavaScript array map, we use the Promise.all method.

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 *