[英]Angular Promises using $q.all
我有一系列物品。 對於該數組中的每個項目,我都需要進行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
分配給this new array to the current array
。
$q.all(promises).then(function(result){
currentBatches = itemProgress;
});
我究竟做錯了什么?
為什么currentBatches = migrationProgress; inside $q.all
currentBatches = migrationProgress; inside $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()
生成的HttpWrapper.send()
,並將其作為promises數組的一項。 看一下map()文檔 :回調應該是一個產生新數組元素的函數。 沒有return語句,該元素將是undefined
。 因此,$ q.all調用會立即解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.