0

For understanding my situation, I have created plunkr. I need the callback when all async requests get executed. Note: async functions are called recursively in the loop.

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;
                };
            }]);
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
Sanjay Gupta
  • 186
  • 2
  • 11

0 Answers0