2017-06-20 83 views
1

我有一系列的项目。对于该数组中的每个项目,我需要进行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正在评估之前为每个项目执行最上面的块。我该如何解决它?

+1

您需要在地图调用中使用return语句才能开始。你正在创造承诺,但你没有回报。 – matmo

回答

4

您应该在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()产生,并把它作为承诺阵列的项目。看看map() docs:回调应该是一个产生新数组元素的函数。没有return语句,元素将是undefined。因为它$ q.all呼叫立即解决。

+1

感谢您的解释。除了出色的答案之外,这有很大的帮助。欢呼:) – StrugglingCoder

+0

不客气! :) –