Javascript 使用$q.all的角度承诺
我有一系列的物品。对于该数组中的每个项,我都需要进行API调用 只有在对项目的所有调用完成后,才有我想继续Javascript 使用$q.all的角度承诺,javascript,angularjs,arrays,promise,Javascript,Angularjs,Arrays,Promise,我有一系列的物品。对于该数组中的每个项,我都需要进行API调用 只有在对项目的所有调用完成后,才有我想继续 var itemProgress = []; var promises = currentBatches.map(function(batch){ HttpWrapper.send('/api/'+batch.job_id+'/progress', { "operation": 'GET' }) .then(function(result) { batch.
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;
});
我做错了什么
为什么currentbacks=migrationProgress;在$q内,所有
都将在对每个项执行最顶层块之前进行计算。如何修复它?您应该在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()生成的承诺,并将其作为承诺数组的一项。看看:回调应该是一个生成新数组元素的函数。如果没有return语句,元素将未定义
。因此,$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()生成的承诺,并将其作为承诺数组的一项。看看:回调应该是一个生成新数组元素的函数。如果没有return语句,元素将未定义
。因此,$q.all调用立即得到解决。您需要在map调用中使用return语句。您正在创建承诺,但没有返回。首先,您需要在map调用中包含一个return语句。你在创造承诺,但你没有回报。谢谢你的解释。除了极好的答案外,这还帮了大忙。谢谢你的解释。除了极好的答案外,这还帮了大忙。干杯:)