Having a bit of trouble with Angular's asynchronization. Basically, I am looping through several cards. Cards of a certain two types require an API call, while cards not of those types don't require any API calls. After looping through all the cards, the array of finished cards is returned, but I am only getting back the ones that don't require any API calls.
This is a quick mockup I made of how it's working:
// If color of colorCard is blue, it needs 2 API calls
// If color of colorCard is red, it needs 1 API call
// If color of colorCard is yellow, it doesn't need an API call
// Pretend for this example that colorCards has one yellow card, one blue card, and two red cards
var buildCards = function() {
var finishedArray = [];
var promises = [];
colorCards.forEach(function(e, i){
if (e.color === 'blue') {
promises.push(firstBlueApiCall);
var firstBlueIdx = 0;
promises.push(secondBlueApiCall);
var secondBlueIdx = 1;
} else if (e.color === 'red') {
promises.push(redApiCall);
var redIdx = 0;
}
// If card is blue or red, complete API calls before pushing to finishedArray
if (promises.length > 0) {
$q.all(promises).then(function(response) {
if (e.color === 'blue') {
e.firstBlueData = response[firstBlueIdx];
e.secondBlueData = response[secondBlueIdx];
} else if (e.color === 'red') {
e.redData = response[redIdx];
}
finishedArray.push(e);
promises = [];
});
// If card is yellow, push to finishedArray without making any API calls
} else {
finishedArray.push(e);
promises = [];
}
})
return finishedArray;
}
In this example, the finishedArray that's returned only ever contains the one yellow card that didn't require an API call instead of all four cards. How can I get that 'return finishedArray' to wait until the red/blue cards have completed their API calls?