When I attempt to fetch multiple JSON files in a loop, I encounter an issue where the callback function only retains the last key of the loop for each result.
Here is how it is called:
deckbuilderApp.factory('DeckFactory', ['$http', '$rootScope', 'DataFactory', function($http, $rootScope, DataFactory) {
var cardColors = {"white":{}, "blue":{}, "black":{}, "red":{}, "green":{}, "colorless":{}};
var cardColorsCheck = {"white":true, "blue":true, "black":true, "red":true, "green":true, "colorless":true};
return {
fetchCardColors: function() {
for (key in cardColors) {
if (cardColors.hasOwnProperty(key)) {
DataFactory.cardColors(key, function(cardIds) {
console.log("GOT COLORS FOR " + key);
cardColors[key] = cardIds;
});
}
}
}
}
}
This is how it is requested:
deckbuilderApp.factory('DataFactory', function($http) {
return {
cardColors: function(color, callback) {
$http({
method: 'GET',
url: 'js/cardColors/' + color + '.json'
}).success(callback)
}
}
}
Although the data is successfully fetched, the log always displays "GOT COLORS FOR colorless" as it processes the last key in the loop.