2014-04-28 80 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