qazzu
qazzu

Reputation: 411

Is there a way to check if the POST is finished processing in angularjs

Is there a way to check if my 5 posts are done and when it's done processing it will call the http://sample-site/users/userList.

  POST http://sample-site/users/addUser/  200 OK
  POST http://sample-site/users/addUser/  200 OK
  POST http://sample-site/users/addUser/  200 OK
  POST http://sample-site/users/addUser/  200 OK
  POST http://sample-site/users/addUser/  200 OK

Is it possible?

I have this code:

  $scope.addUser= function(user){
  user.forEach(function(v, i){
     $http.post('addUser', $.param(v), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
       .success(function(response) {
           if (!response.status) {

           } else {
               $scope.errors = response.errors;
           }
        }).error(function() {
      });
    });
   }

Thanks

Upvotes: 0

Views: 96

Answers (4)

Arun James
Arun James

Reputation: 88

You can use $q.all, something like this.

var promise1 = $http({method: 'GET', url: 'a/pi-one-url', cache: 'true'});
var promise2 = $http({method: 'GET', url: '/api-two-url', cache: 'true'});

$q.all([promise1, promise2]).then(function(data){
    console.log(data[0], data[1]);
});

Upvotes: 1

Kunal Kapadia
Kunal Kapadia

Reputation: 3333

$http.post return a promise. So you can save the promise return by each call to $http.post in an array and then use $q.all(promises) to wait till all promises are resolved.

$scope.addUser = function (user) {
    var promises = [];
    user.forEach(function (v, i) {
        var promise = $http.post('addUser', $.param(v), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .success(function (response) {
                if (!response.status) {

                } else {
                    $scope.errors = response.errors;
                }
            }).error(function () {
            });

        promises.push(promise);
    });

    $q.all(promises).then(function (results) {
        // all the promises have been resolved
        // results is an array which contains the resolved promise value in that order
        // call http://example.com/users/userList
    });
}

Upvotes: 1

Tjaart van der Walt
Tjaart van der Walt

Reputation: 5179

You can use $q.all

var promises = [];
user.forEach(function(v, i){
    promises.push($http.post('addUser', $.param(v), { headers: { 'Content-Type':     'application/x-www-form-urlencoded' }}))
});
$q.all(promises).then(function(data){
    for (var i = 0; i < data.length; i++) {
    if (!data[i].response.status) {

       } else {
           $scope.errors = data[i].response.errors;
       }
     }
   });

Upvotes: 1

marcosspn
marcosspn

Reputation: 386

It can be done using $q.all

Check documentation here:

https://docs.angularjs.org/api/ng/service/$q#all

Upvotes: 3

Related Questions