Ben Kilah
Ben Kilah

Reputation: 3475

AngularJs Promises within Promise

Hey guys I'm posting some data to a server then based on a couple of variables posting again to a different url inside the loop.

So far I'm using as an example:

    $scope.items = [{'name':'Test1','hasd':1,'hase':1},{'name':'Test2','hasd':0,'hase':1}];
    var promises = [];

    angular.forEach($scope.items,function(obj) {
    promises.push($http({
        type:'post',
        url:'test',
        data:obj
      }).then(function(response) { 
          if(response.status==201) {
             //do another http call
             if(obj.hasd==1) {
                $http({}).then(function() { 
                    var something=1; 
                });
             }
          }
        }));

   $q.all(promises).then(function(){
      alert('done');
   });

The problem I am having is that it's only looking at the initial $http call's promise rather then any internal calls. Is there a way to have all the $http calls be added to the promise inside the loop?

Cheers, Ben

Upvotes: 2

Views: 3673

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22933

Try changing this:

$http({}).then(function() { 
  var something=1; 
});

To:

return $http({}).then(function() { 
  var something=1; 
});

That means that your "outer" promise that you add to the promises array won't be resolved until the "inner" promise has completed.

The reason for this is that a then handler can return a value or another promise. To understand this, you need to understand that all then handlers creates a new promise. So there will always be one dangling promise at the end that no one cares about.

If your then handler doesn't return anything, then Javascript will (sort of) return undefined for you. So the promise created by your then handler will be resolved immediately with the value you returned, or undefined if you didn't return anything. But you can also return a new promise which is what gets passed back into your promises array.

Upvotes: 10

Related Questions