3

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

user3108740
  • 43
  • 1
  • 3
  • 5
    Use [`$q.all()`](https://docs.angularjs.org/api/ng/service/$q#all). – Blackhole Apr 28 '14 at 14:15
  • In this situation impossible to use $q.all(), because function ServiceA.functionA need to use result of promiseA. – iKBAHT Apr 29 '14 at 07:08
  • It looks to me like you already are. The promise returned by `getInfo` will be resolved with `info` after its `favorites` item has been modified in the final callback. – Michal Charemza May 03 '14 at 16:40

4 Answers4

1

You need to use $q.all()

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

Community
  • 1
  • 1
Sam
  • 15,336
  • 25
  • 85
  • 148
1

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

Community
  • 1
  • 1
Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
0
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.

km6zla
  • 4,787
  • 2
  • 29
  • 51
  • you manually call it with `$q.reject(reason)` in the error callbacks of the other requests. – km6zla Apr 29 '14 at 16:00
0
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
})
iKBAHT
  • 644
  • 6
  • 17