AngularJS - wait for all async calls inside foreach finish
by Alfeu Santos
HTML
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div ng-app='MyApp' ng-controller='MyController'></div>
JavaScript
var app = angular.module('MyApp',[]);
app.controller('MyController',['$scope','$q',function($scope,$q){
$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 loop done');
}, 2000);
});
$q.all(loopPromises).then(function () {
console.log('foreach loop completed. Do something after it...');
});
}]);