我完成了三个并行承诺或api请求,我需要根据第二个承诺调用另一个api请求然后最终调用.then($ q.all
这是代码
getAllLocations() {
//make a promise call for all here .
var promise = [];
̶p̶r̶o̶m̶i̶s̶e̶.̶p̶u̶s̶h̶(̶t̶h̶i̶s̶.̶g̶e̶t̶A̶l̶l̶L̶o̶c̶a̶t̶i̶o̶n̶s̶(̶I̶d̶)̶.̶t̶h̶e̶n̶(̶
promise.push(this.getLocations(Id).then(
(locationsData) => {
this.locations = locationsData;
}));
promise.push(this.getAllStates(Id).then(
(resp) => {
this.states = resp.data;
}));
promise.push(this.getTerritories(Id).then(
(resp) => {
this.utilizations = resp.data;
}));
$q.all(promise).then(() => {
var nodePromise = [];
angular.forEach(this.states, function(node) {
var nodeId = node.Id;
nodePromise.push(this.getNodeHealthSummary(nodeId).then(
(resp) => {
node.healthStatus = resp.data.operationalStatus;
}));
this.$q.all(nodePromise).then(() => {
var index = this.states.indexOf(node);
this.states.splice(index, 1, angular.copy(node));
});
},this);
}).then(() => {
for (var i = 0; i < this.locations.length; i++) {
//do something here with this.states
}
this.gridData = this.locations;
});
}
当我在this.locations的for循环中时,我需要使用healthStatus属性更新this.states。 (the last.then)
但是,我看到this.locations for循环是在每个状态上设置node.healthStatus属性之前完成的。
如何做到这一点?使用Promise而不是$ q很好。请让我知道如何实现这一点,我已经徒劳无功
答案 0 :(得分:1)
在$q.all
循环的每次迭代中调用内部forEach
,并获取在forEach
循环期间填充的数组作为参数。这显然是不对的;它应该只被调用一次,其结果应该是then
回调的返回值。
所以不是这个块:
$q.all(promise).then(() => {
var nodePromise = [];
angular.forEach(this.states, function(node) {
var nodeId = node.Id;
nodePromise.push(this.getNodeHealthSummary(nodeId).then(
(resp) => {
node.healthStatus = resp.data.operationalStatus;
}));
this.$q.all(nodePromise).then(() => {
var index = this.states.indexOf(node);
this.states.splice(index, 1, angular.copy(node));
});
},this);
}).then( ......
这样做:
$q.all(promise).then(() => {
return $q.all(this.states.map((node, index) => {
return this.getNodeHealthSummary(node.Id).then(resp => {
node.healthStatus = resp.data.operationalStatus;
this.states[index] = angular.copy(node);
});
}));
}).then( ......