Categories
JavaScript Answers

How to use Array.prototype.map with Promise.all in JavaScript?

Spread the love

Sometimes, we want to use Array.prototype.map with Promise.all in JavaScript.

In this article, we’ll look at how to use Array.prototype.map with Promise.all in JavaScript.

How to use Array.prototype.map with Promise.all in JavaScript?

To use Array.prototype.map with Promise.all in JavaScript, we should call map with a callback that returns a promise.

For instance, we write:

(async () => {
  const items = [1, 2, 3]
  const vals = await Promise.all(items.map(async (it) => it * 2))
  console.log(vals)
})()

to calls items.map with an async function as the callback.

It returns a promise that resolves to the items entry times 2.

Then we call Promise.all with the array of promises we created with map.

Therefore, vals is [2, 4, 6].

Conclusion

To use Array.prototype.map with Promise.all in JavaScript, we should call map with a callback that returns a promise.

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 *