为了解我的情况,我创建了plunkr。当所有异步请求都被执行时,我需要回调。 注意:异步函数在循环中递归调用。
angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$q", "$timeout", function ($scope, $q, $timeout) {
var promises = [];
$scope.result='';
$scope.runAsync = function () {
var listOfItems = [1, 2, 3, 4, 5];
$scope.result='';
// Iterating list of items.
for (var j = 0; j <= 5; j++) {
promises.push($scope.myAsyncFun(j, promises));
}
$q.all(promises).then(function () {
$scope.result+=' Chain finished!';
});
};
$scope.myAsyncFun = function (val, promises, deferred) {
if (deferred == null) {
deferred = $q.defer();
}
$timeout(function () {
$scope.result+=' Item executed: ' + val;
if (val % 2 == 0) {
for (var k = 0; k < val; k++) {
promises.push($scope.myAsyncFun(k, promises, deferred));
}
}
else {
deferred.resolve();
}
}, 1000);
return deferred.promise;
};
}]);