我有这段代码:
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!');
});
});
});
});
});
现在我想知道什么时候一切都解决了,我猜我应该使用$ q.all()。问题是调用依赖于前面的步骤输出,因为我正在对每个先前的输出进行调用,应该在哪里放置承诺?
级别总是3深,因此不需要递归。
任何形式的投入都将受到赞赏!
答案 0 :(得分:0)
是的,您使用的是all()
,但仍需要嵌套它们:
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);
});