2014-04-28 75 views
3

我对多重承诺有一点疑问。 我该如何等待所有承诺才能完成,以获得最终结果。AngularJS:多重承诺全部等待

见我的代码:

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); 
         });  
     });  
}, 

我的目标是返回值之前等待ServiceA.functionA的结果。

感谢

KL

+5

使用['$ q.all()'](https://docs.angularjs.org/api/纳克/服务/ $ q#全部)。 – Blackhole

+0

在这种情况下不可能使用$ q.all(),因为函数ServiceA.functionA需要使用promiseA的结果。 – iKBAHT

+0

它看起来像我,你已经是。 'getInfo'返回的promise在其最后一次回调中被修改为'favorites'后会用'info'解决。 –

回答

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; 
} 

再后来,你可以调用该函数,并得到一个承诺...

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

successCallback只会被调用一次resolve已在延迟对象上被调用。

+0

但errorCallback从未被称为 – iKBAHT

+0

您在其他请求的错误回调中使用'$ q.reject(reason)'手动调用它。 –

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

使用这样的:

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 
}) 
+0

总是鼓励至少给出一点解释你的代码在做什么。 – dirkk