【问题标题】:Angular Promises using $q.all使用 $q.all 的 Angular Promise
【发布时间】:2017-11-23 08:14:50
【问题描述】:

我有一系列项目。对于该数组中的每一项,我都需要进行 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

$q.all(promises).then(function(result){

    currentBatches = itemProgress;
});

我做错了什么?

为什么currentBatches = migrationProgress; inside $q.all为每个项目执行最高块之前被评估。我该如何解决?

【问题讨论】:

  • 您需要在 map 调用中使用 return 语句才能开始。您正在创建承诺,但您没有返回它们。

标签: javascript angularjs arrays promise


【解决方案1】:

您应该在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,并将其作为promises 数组的一项。看看map() docs:回调应该是一个产生新数组元素的函数。如果没有 return 语句,元素将是 undefined。因此,$q.all 调用会立即解决。

【讨论】:

  • 感谢您的解释。除了出色的答案之外,这也有很大帮助。干杯:)
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2015-11-20
  • 2017-08-04
  • 1970-01-01
  • 2016-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多