2014-10-08 38 views
2

使用Angular.js和Restangular,當一個循環內的所有子請求都完成時,如何鉤入?例如:使用Angular.js和Restangular,當一個循環內的所有子請求都完成時,我怎樣才能鉤入?

Restangular.all('clusters').getList().then(function(clusters) { 
    clusters.forEach(function(cluster, index) { 
     cluster.get().then(function(response) { 
      //some logic 
     }); 
    }); 
}); 

基本上我需要知道什麼時候所有子請求cluster.get()是完整的,然後做一些事情。有沒有一種乾淨的方式來做到這一點?

回答

2

您應該可以使用$q.all方法來等待所有請求。它會這樣工作:

Restangular.all('clusters').getList().then(function(clusters) { 
    var promises = clusters.map(function(cluster, index) { 
     return cluster.get().then(function(response) { 
      //some logic 
     }); 
    }); 

    return $q.all(promises); 
}).then(function() { 
    // logic for when all of the get methods are complete 
}); 
相關問題