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.