0

I have this code:

GamesStatsService.query({ level: 1 }).$promise.then(function(consoles) {
        $scope.consoles = consoles;
        _.each(consoles, function(c) {
            GamesStatsService.query({ consoleName: c.id, level: 2 }).$promise.then(function(regions) {
                c.regions = regions;
                _.each(regions, function(r) {
                    GamesStatsService.query({ consoleName: c.id, regionName: r.id, level: 3 }).$promise.then(function(subRegions) {
                        r.subRegions = subRegions;
                        console.log('(maybe) finished loading, notify subscriber!');
                    });
                });
            });
        });
    });

Now I want to know when everything is resolved, and I'm guessing I should use $q.all() for this. The problem is that the calls are dependant on the previous steps output and since I'm doing the calls on each previous output, where should the promise(s) be placed?

The levels are always 3 deep so recursion shouldn't be necessary.

Any kind of input would be appreciated!

Bergi
  • 630,263
  • 148
  • 957
  • 1,375

1 Answers1

0

Yes, you'd use all() but you still need to nest them:

GamesStatsService.query({ level: 1 }).$promise.then(function(consoles) {
    $scope.consoles = consoles;
    return $q.all(_.map(consoles, function(c) {
        return GamesStatsService.query({ consoleName: c.id, level: 2 }).$promise.then(function(regions) {
            c.regions = regions;
            return $q.all(_.map(regions, function(r) {
                return GamesStatsService.query({ consoleName: c.id, regionName: r.id, level: 3 }).$promise.then(function(subRegions) {
                    r.subRegions = subRegions;
                    return subRegions;
                });
            })).then(function(allSubRegions) {
                return regions;
            });
        });
    })).then(function(allRegions) {
        return consoles;
    });
}).then(function(consoles) {
    console.log('finished loading of all regions and subregions for', consoles);
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375