Categories
JavaScript Answers

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

Spread the love

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

For instance, we write

const promises = array.map(async (element) => {
  const data = await developer.getResources(element);
  name = data.items[0];
  const response = await developer.getResourceContent(element, file);
  fileContent = atob(response.content);
  files.push({
    fileName,
    fileType,
    content,
  });
});

await Promise.all(promises);

to call array.map with an async function which returns a promise.

Therefore, promises is an array of promises.

And we call Promise.all with promises to return a promise that resolves when all the promises are resolved.

The promises are run in parallel.

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 *