[英]Angular Promises using $q.all
我有一系列物品。 对于该数组中的每个项目,我都需要进行API调用。
仅在所有对项目的调用完成之后,才需要我继续。
var itemProgress = [];
var promises = currentBatches.map(function(batch){
HttpWrapper.send('/api/'+batch.job_id+'/progress', { "operation": 'GET' })
.then(function(result) {
batch.succeeded_time_pct = result.succeeded_by_time_pct; // I add one property to each of the item
itemProgress.push(batch); // I push it to a new array
},function(errorResponse) {
console.log(errorResponse);
});
});
在这里,我试图在对每个项目进行an API call for each of the items
后向每个项目添加new property
。
当所有调用完成后,我想this new array to the current array
分配给this new array to the current array
。
$q.all(promises).then(function(result){
currentBatches = itemProgress;
});
我究竟做错了什么?
为什么currentBatches = migrationProgress; inside $q.all
currentBatches = migrationProgress; inside $q.all
内容将在对每个项目执行最高块之前进行评估。 我该如何解决?
您应该在map()
回调中放入return
。
var itemProgress = [];
var promises = currentBatches.map(function(batch){
// return the following promise
return HttpWrapper.send('/api/'+batch.job_id+'/progress', { "operation": 'GET' })
.then(function(result) {
batch.succeeded_time_pct = result.succeeded_by_time_pct; // I add one property to each of the item
itemProgress.push(batch); // I push it to a new array
},function(errorResponse) {
console.log(errorResponse);
});
});
$q.all(promises).then(function(result){
currentBatches = itemProgress;
});
这将返回由HttpWrapper.send()
生成的HttpWrapper.send()
,并将其作为promises数组的一项。 看一下map()文档 :回调应该是一个产生新数组元素的函数。 没有return语句,该元素将是undefined
。 因此,$ q.all调用会立即解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.