0

I am trying to make few ajax call inside a loop. I want to print a message only when my last ajax is successful. Any suggestions what I am doing wrong here.

        $scope.defer = $q.defer();
        $scope.promises = [];
        $scope.array = [1,2,3,4,5,6,7,8,9,10];
        $scope.makecall = function(){
            angular.forEach($scope.array, function(index){
                $timeout(function() {
                   var promise = $http({
                        url   : 'https://jsonplaceholder.typicode.com',
                        method: 'GET',
                    }).
                    success(function(data){
                    });

                    $scope.promises.push(promise);
                }, index * 2000);
            });
            return $scope.defer.promise;
        }
        $scope.makecall();
        $q.all($scope.promises).then(function(){
            console.log('over!');
        });
Aditya Kumar
  • 165
  • 1
  • 1
  • 16

1 Answers1

1

I think you can check the SO

Wait for all promises to resolve

$q.all([one.promise, two.promise, three.promise]).then(function() {
    console.log("ALL INITIAL PROMISES RESOLVED");
});

var onechain   = one.promise.then(success).then(success),
    twochain   = two.promise.then(success),
    threechain = three.promise.then(success).then(success).then(success);

$q.all([onechain, twochain, threechain]).then(function() {
    console.log("ALL PROMISES RESOLVED");
});

you may also check

function outerFunction() {

var defer = $q.defer();
var promises = [];

function lastTask(){
    writeSome('finish').then( function(){
        defer.resolve();
    });
}

angular.forEach( $scope.testArray, function(value){
    promises.push(writeSome(value));
});

$q.all(promises).then(lastTask);

return defer.promise;

}

Community
  • 1
  • 1
Nair Athul
  • 823
  • 9
  • 21