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

promise.all for loop
promise for loop node js
promise inside foreach
javascript promise for loop
promise inside for loop
async.foreach callback
synchronous for loop javascript
async await while loop javascript

I am running a forEach loop on an array and making two calls which return promises, and I want to populate an object say this.options, and then do other stuff with it. Right now I am running into the async issue if i use the following code sample and i get into the then function first.

$.when.apply($, someArray.map(function(item) {
    return $.ajax({...}).then(function(data){...});
})).then(function() {
    // all ajax calls done now
});

This is working code below, but it only works for the first element in the array, because I call the resulting function in the .then of the response. I want to do all the fetch first for all elements of the array and then call the resulting function to do something.

array.forEach(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
            });
            self.resultingFunction(self.files)
        }).catch ((error) = > {
            console.log('Error: ', error);
        })
});

How do i populate the self.files object after the forEach loop is complete, and then call the resulting function with the files 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.

What about promises in loops?, I hear that people “don't really understand Promises” at least a few times a of the array to a function as one of arguments (function returns a Promise). an object with a value that was to be used inside the same loop. The above case had a nice async/await syntax, while we pretended to use Promises. JavaScriptforEach with promises. Example#. It is possible to effectively apply a function (cb) which returns a promise to each element of an array, with each element waiting to be processed until the previous element is processed. function promiseForEach(arr, cb) { var i = 0; var nextPromise = function () { if (i >= arr.length) { // Processing finished.

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.

JavaScript async and await in loops, I am running a forEach loop on an array and making two calls which return promises, and I want to populate an object say this.options , and then do other stuff  At the end we needed to pass array of values (not promises) to another function. In addition, the function was returning an object with a value that was to be used inside the same loop. The main aim was to get the best performance results and good code readability.

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().

Foreach Promise, Examples of such loops that require a fallback include forEach , map , filter , and reduce . We'll look If you use await in a map , map will always return an array of promise. Since promises are always truthy, everything item in the array passes the filter. If you fill this in, you will be marked as a spammer. The in keyword used in foreach loop to iterate over the iterable-item (which is here the array or the collections). The in keyword selects an item from the iterable-item or the array or collection on each iteration and store it in the variable (here variable_name).

The following code is simple understanding of sync using Promise.

let numArr = [1,2,3,4,5];
let nums=[];

let promiseList = new Promise(function(resolve,reject){
  setTimeout(()=>{
        numArr.forEach((val)=>{
        nums.push(val);
    });
    resolve(nums);
 },5000)
})


Promise.all([promiseList]).then((arrList)=>{
  arrList.forEach((array)=>{
    console.log("Array return from promiseList object ",array);    
  })

 });

Above example will hold array nums for 5 sec. and it will print on console after it release.

Asynchronous code inside an array loop, I am running a forEach loop on an array and making two calls which return promises, and I want to populate an object say this. Let's go ahead and use this  In this tutorial, we are going to learn different ways to loop through an array of objects in JavaScript. First way: ForEach method. In es6 we have a forEach method which helps us to iterate over the array of objects.

Making array iteration easy when using async/await, I have to make a loop through an array, then with each item make an async Because async callback runs when the promise is resolved, outside of the The principle to solve this problem is to put the array[i] inside a scope,  files.reduce( (lastPromise, file) => lastPromise.then( () => fs.readFile(file, 'utf8') ), Promise.resolve() ) Or you can create a forEachAsync to help but basically use the same for loop underlying. Array.prototype.forEachAsync = async function(cb) { for(let x of this) { await cb(x); } } share.

How to use Promise.all and ForEach to make ajax call per array item , Node.js version 8 is out, and we're finally able to use async/await The result is not going to be an Array of plain user objects, but an Array of Promises. Using a for-of loop instead of forEach() is going to work, but as you  The "for loop" repeatedly executes astatements until the specified execution evaluates to false whereas a foreach loop repeats a group of embedded statements for each element in array or object collection. The following examples shows how to use a foreach loop in TypeScript. Use the following instructions to create a program using a for

Array.prototype.forEach(), JQuery AJAX does not use native JS promises. You can observe this by the way they defined a success and error callback. You can explore  JavaScript Array Loops. There are different ways to loop over arrays in JavaScript, but it can be difficult choosing the right one. Plus keeping each method straight can drive a developer nuts. There is a classic JavaScript for loop, JavaScript forEach method and a collection of libraries with forEach and each helper methods.

Comments
  • Why forEach when you clearly need map?
  • @YuryTarabanko I used a map and that didn't work either. I also tried the approach in the answer but with a $.when.apply($, promises).then(), but didn't work either. I think it did not work because I was did not do it the ES6 way.
  • Should be Promise.all, not Promises (plural).
  • Why are you manually creating a Promise? It all looks like getResources already returns one
  • @YuryTarabanko Out of curiosity, if you would push the promises returned from getResources directly to the promises array instead of wrapping it in your own, is it guaranteed that all individual finalization handlers are called first before the finalization handler of Promise.all()? If not, creating your own promises seems necessary.
  • @TimoSta Not directly from getResources but the last promise you get in chain getResources().then(fn1).then(fn2).catch(). Every time you call then you get a new promise. And sure fn1 will be called before fn2 and before finalization handler. Simply because promises will pass the result of fn1 to fn2 and then to finalization handler (as corresponding array element).
  • Ah, I see. Learned something new today! Thanks :-)
  • Could you highlight what you have changed so that we don't have to read every line?
  • Have added a new sentence at the end explaining what I did.