How to handle multiple async tasks in angular.js?
Promises and $q.all
(ref) are your friends.
In more detail, you will have to make a promise for each call (if the call itself does not return one), push them in an array and call $q.all(promises).then(allFinished)
. Naive case, where $update()
does not return a promise:
function callUpdate(x, promises) { var d = $q.defer(); x.$update({stateId: $scope.states[i].id}, function() { someFunction(); d.resolve(); // it may be appropriate to call resolve() before someFunction() depending on your case }); promises.push(d.promise);}...var promises = [];for (var i = 0; i < $scope.states.length; i++) { $scope.states[i].someProperty = someNewValue; callUpdate($scope.states[i], promises);}$q.all(promises).then(function() { // called when all promises have been resolved successully});
The reason for the existence of callUpdate()
is to encapsulate the deferred object handling and return the promise.