Struggling with the asynchronous nature of Angular, I'm faced with a challenge. My task involves looping through various cards where certain types require API calls while others do not. However, upon completion of the loop, only the cards that do not need API calls are being returned.
To illustrate how it's currently functioning:
// If color of colorCard is blue, it requires 2 API calls
// If color of colorCard is red, it requires 1 API call
// If color of colorCard is yellow, no API call needed
// For this example, let's say there's one yellow card, one blue card, and two red cards in colorCards
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;
}
// Only push to finishedArray after completing API calls for blue or red cards
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 = [];
});
// For yellow cards, simply push to finishedArray without any API calls
} else {
finishedArray.push(e);
promises = [];
}
})
return finishedArray;
}
The issue arises when the 'return finishedArray' statement only includes the yellow card without waiting for the red/blue cards to finish their API calls. How can I make sure all four cards are included in the final array?