Search code examples
javascriptangularjsrestangular

Using Angular.js and Restangular, how can I hook into when all child requests inside a loop are complete?


Using Angular.js and Restangular, how can I hook into when all child requests inside a loop are complete? For example:

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

Essentially I need to know when all child requests to cluster.get() are complete and then do something. Is there a clean way of doing this?


Solution

  • You should be able to use the $q.all method to await all of the requests. It would work something like this:

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