【发布时间】:2017-12-08 08:12:49
【问题描述】:
一旦这三个都完成后,我有 3 个并行承诺或 api 请求,我需要根据第二个承诺调用另一个 api 请求,然后最后调用 .then( of $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。 (最后一个.then)
但是,我看到 this.locations for 循环是在每个状态上设置 node.healthStatus 属性之前提前完成的。
如何做到这一点?使用 Promises 而不是 $q 很好。请让我知道我怎样才能做到这一点,我已经尝试了一切都是徒劳的
【问题讨论】:
-
代码是否对
getAllLocations函数进行了递归调用? -
我很确定您的意思是将
$q.all放在循环之外? -
尝试使用
map而不是forEach -
错字,对于 getAllLocations,它的 getLocations() 在承诺中,我在我的实际代码中正确地使用了它
-
如果我把 $q.all 放在外面,我需要将数组与节点拼接并复制新节点,我不能在 foreach 循环之外进行操作,因为节点引用不存在
标签: javascript angularjs promise angular-promise es6-promise