Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs for loop promises callback

Tags:

http

angularjs

I was wondering if there is any possibility to get a callback at the end of a series of requests. I'm attaching an example code so you can better understand :

for (var i = 0; i < $scope.array.length; i++) {
    factory.getX($scope.array[i].id)
        .success(function (_response) {
            /* call function if it's the last request in the for loop*/
        })
        .error(function (_err) {
            $scope.displayAlert(_err)
        })
}

In the factory object, I have a $http.get() function. Thanks !

like image 816
alexsc Avatar asked Jul 19 '26 07:07

alexsc


2 Answers

If you want to have a callback when all the requests are completed you could save all the promises that are created in a array and make a common promise with var allRequests = $q.all(arrayOfPromises)

You could then do allRequests.then(callback) to implement your callback

like image 130
Ricconnect Avatar answered Jul 21 '26 21:07

Ricconnect


Thank you all, I've solved the problem like this :

 var promises = $scope.array.map(function (item) {
                        return factory.getX(item.id)
                            .success(function (_response) {

                            })
                            .error(function (_err) {
                                $scope.displayAlert(_err)
                            })
                    })

 $q.all(promises).then(function () {
        console.log("Solved all the promises")
    }
like image 32
alexsc Avatar answered Jul 21 '26 20:07

alexsc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!