How to use promise in forEach loop of array to populate an object How to use promise in forEach loop of array to populate an object arrays arrays

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


Promise.all() will be helpful here:

var promises = [];array.forEach(function(element) {    promises.push(        developer.getResources(element)            .then((data) = > {                name = data.items[0];                return developer.getResourceContent(element, file);            })            .then((response) = > {                fileContent = atob(response.content);                self.files.push({                    fileName: fileName,                    fileType: fileType,                    content: fileContent                });            }).catch ((error) = > {                console.log('Error: ', error);            })    );});Promise.all(promises).then(() =>     self.resultingFunction(self.files));

This starts the AJAX call for each of the items, adds the result of each call to self.files once the call is complete and calls self.resultingFunction() after all calls have been completed.

Edit: Simplified based on Yury Tarabanko's suggestions.


Just a slight variation of the accepted solution above would be:

var promises = array.map(function(element) {      return developer.getResources(element)          .then((data) = > {              name = data.items[0];              return developer.getResourceContent(element, file);          })          .then((response) = > {              fileContent = atob(response.content);              self.files.push({                  fileName: fileName,                  fileType: fileType,                  content: fileContent              });          }).catch ((error) = > {              console.log('Error: ', error);          })});Promise.all(promises).then(() =>     self.resultingFunction(self.files));

I used Array.map instead of Array.forEach, which means I don't need to create an empty array first, I just re-use the existing one.


You might look at this answer to a similar question for an excellent hint. The solution given there uses Array#reduce() to avoid having to accumulate all of the Promises before doing any of the work rather than using Promise.all().