[英]multiple promises running in parallel, $q.all needs chaining?
I have 3 parallel promises or api requests once all teh three are done, I need to call another api request based on the second promise and then finally call .then( of $q.all 一旦完成了三个,我就有了3个并行的Promise或api请求,我需要根据第二个Promise调用另一个api请求,然后最终调用$ q.all的.then(
Here is the code 这是代码
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;
});
}
I need this.states updated with healthStatus property when i am in the for loop of this.locations. 当我在this.locations的for循环中时,我需要使用healthStatus属性更新的this.states。 ( the last.then )
(最后一个)
However , i see that this.locations for loop is done ahead before the node.healthStatus property is set on each state. 但是,我看到要在每个状态上设置node.healthStatus属性之前,先完成this.locations for循环。
How can this be done? 如何才能做到这一点? Using Promises instead of $q is fine.
使用Promises代替$ q很好。 Please let me know how can i achieve this , i have tried all in vain
请让我知道我该怎么做到
The inner $q.all
is called in each iteration of the forEach
loop, and gets as argument the array that is being populated during that forEach
loop. 内部的
$q.all
在forEach
循环的每次迭代中被调用,并获取在该forEach
循环中正在填充的数组作为参数。 This is obviously not right; 这显然是不对的。 it should be called only once, and its result should be the return value of the
then
callback. 它只能被调用一次,其结果应该是
then
回调的返回值。
So instead of this block: 因此,代替此块:
$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( ......
Do this: 做这个:
$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( ......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.