StrugglingCoder StrugglingCoder - 1 month ago 5
Javascript Question

Angular Promises using $q.all

I have an array of items. For each of the item in that array, I need to make an API call.

Only after all the calls for the items are finished, then only I want to proceed.

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);
});
});


Here I am trying to add a
new property
to each of the items after making
an API call for each of the items
.

And when all the calls are done,
I want to assign
this new array to the current array
.

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

currentBatches = itemProgress;
});


What am I doing wrong?

Why
currentBatches = migrationProgress; inside $q.all
is being evaluated before the topmost block gets executed for each of the items. How can I fix it?

Answer Source

You should put a return inside the map() callback.

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;
});

This will return the promise generate by HttpWrapper.send() and put it as an item of the promises array. Take a look in the map() docs: the callback should be a function that produces an element of the new array. Without the return statement the element will be undefined. Because of it the $q.all call is resolved immediately.