我有一系列的项目。对于该数组中的每一项,我都需要进行 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);
});
});
在对每个项目进行 API 调用
之后,我尝试为每个项目添加一个新属性
。
当所有调用完成后,
我想将 这个新数组分配给当前数组
。
$q.all(promises).then(function(result){
currentBatches = itemProgress;
});
我做错了什么?
为什么 currentBatches = migrationProgress;在 $q.all
中,在为每个项目执行最顶层的 block 之前对其进行评估。我该如何解决?
最佳答案
您应该在 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()
生成的 promise ,并将其作为 promise 数组的一项。看看 map() docs :回调应该是一个生成新数组元素的函数。如果没有 return 语句,元素将是 undefined
。因此 $q.all 调用立即得到解决。
关于javascript - 使用 $q.all 的 Angular Promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44658918/