Categories
JavaScript Answers

How to use promise in forEach loop of array to populate an object with JavaScript?

Spread the love

Sometimes, we want to use promise in forEach loop of array to populate an object with JavaScript.

In this article, we’ll look at how to use promise in forEach loop of array to populate an object with JavaScript.

How to use promise in forEach loop of array to populate an object with JavaScript?

To use promise in forEach loop of array to populate an object with JavaScript, we use the Promise.all method.

For instance, we write

const res = await Promise.all([...arr.map((i) => func())]);

to call Promise.all with an array of functions returned by arr.map.

func returns a promise which is run in parallel by Promise.all.

We get the results from the promises as an array with await.

Conclusion

To use promise in forEach loop of array to populate an object with JavaScript, 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 *