Kanban
Kanban

Reputation: 141

Javascript/Angularjs : wait for promise to be fulfilled before going to the next iteration in foreach Loop

Pretty sure I'm missing something minor here. I'm applying a javascript foreach loop on an array of objects. Withing the loop, I'm making an async call to an api to update data. What I want is foreach loop to wait for the promise to be fulfilled before moving on to the next iteration.

Here's the code sample

entriesToUpdate.forEach(function (item) {   
    SomeService.updateEntry(item).then(function (res) {
        //Do some stuff here.
    });
    //Wait for the above promise to be fulfilled before going to next iteration 
});

Upvotes: 3

Views: 2206

Answers (1)

Xenotoad
Xenotoad

Reputation: 362

You could define a function to process the entries recursively like so:

function updateEntries(entries, i) {
  if(i < entries.length) {
    return SomeService.updateEntry(entries[i]).then(function() {
      return updateEntries(entries, i+1);
    });
  }
}
updateEntries(entriesToUpdate, 0);

Or you could chain your promises.

var promise = SomeService.updateEntry(entriesToUpdate[0]);
for(var i = 1; i < entriesToUpdate.length; i++) {
  promise = promise.then(function() {
    return SomeService.updateEntry(entriesToUpdate[i]);
  });
}

(These examples might not work; I'm not familiar with AngularJS promises. Only ES6 promises)

Upvotes: 3

Related Questions