user3108740
user3108740

Reputation: 43

AngularJS : multiple promise wait all

I have a little question about multiple promise. How can I wait that all promises will be done for return the final result.

See my code :

getInfo : function(){
        return promiseA.then(function(result){
               info  = result;
               //this function have also promises 
               return ServiceA.functionA(info.login)
                      .then(function(favouriteItems){
                          info.favorites = favouriteItems;
                          return $q.when(info);
                       });      
         });       
},

My aims it's to wait the result of ServiceA.functionA before return value.

Thanks

K.L

Upvotes: 3

Views: 918

Answers (4)

Sam
Sam

Reputation: 15771

You need to use $q.all()

This is a good post here on the question: stackoverflow.com/questions/21310964/angularjs-q-all

Upvotes: 1

iKBAHT
iKBAHT

Reputation: 702

getInfo : function() {
  return promiseA.then(function(result){           
    return ServiceA.functionA(result.login).then(function(favouriteItems){
      result.favorites = favouriteItems;
      return result;
    });      
  });       
},

Use like this:

api.getInfo().then(function(result){
  // use result and result.favorites
}, function(err){
  // here you can be if an error occurred in promiseA or in ServiceA.functionA
})

Upvotes: 0

Sten Muchow
Sten Muchow

Reputation: 6701

I wrote an answer to another question stating the solution to this problem using the $q.all approach.

Check it out: AngularJS: Listen to events, one after the other

Upvotes: 1

km6zla
km6zla

Reputation: 4877

function getInfo() {
  var deferred = $q.defer();

  promiseA.then(function(result){
    info  = result;
    // this function have also promises 
    ServiceA.functionA(info.login)
      .then(function(favouriteItems){
         info.favorites = favouriteItems;
           // the magic
           deferred.resolve(info);
           // at this point, you can resolve any value
      });      
    });
  }

  return deferred.promise;
}

then later you can call that function and get a promise...

var promise = getInfo();
promise.then(successCallback, errorCallback, notifyCallback);

The successCallback will only be called once resolve has been called on the deferred object.

Upvotes: 0

Related Questions