2017-06-20 67 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

不客氣! :) –