AngularJS wait for all async calls inside foreach finish
pseudo code using angular's $q service.
requests = [];forEach cardTitle var deferred = $q.defer(); requests.push(deferred); Trello.post('/path', {}, deferred.resolve, deferred.reject);$q.all(requests).then(function(){ // TODO});
For those looking for the answer to the question's title "AngularJS wait for all async calls inside foreach finish", here is a generic way to achieve it, also using angular's $q service:
$scope.myArray = [1, 2, 3, 4, 5, 4, 3, 2, 1];var loopPromises = [];angular.forEach($scope.myArray, function (myItem) { var deferred = $q.defer(); loopPromises.push(deferred.promise); //sample of a long-running operation inside loop... setTimeout(function () { deferred.resolve(); console.log('long-running operation inside forEach loop done'); }, 2000);});$q.all(loopPromises).then(function () { console.log('forEach loop completed. Do Something after it...');});
Here is a working sample.
Have a look at the async library https://github.com/caolan/async.
So you can either run all your asyn functions in parallel or series and your common callback will be executed once all of them are finished.
async.parallel([ function(){ ... }, function(){ ... }], callback);async.series([ function(){ ... }, function(){ ... }]);
Hope it helps.