I try to fetch multiple json files in a loop. The data gets fetched, but in my callback function I'm left with the last key of the loop for each result.
Here is the caller:
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;
});
}
}
}
}
}
And the callee:
deckbuilderApp.factory('DataFactory', function($http) {
return {
cardColors: function(color, callback) {
$http({
method: 'GET',
url: 'js/cardColors/' + color + '.json'
}).success(callback)
}
}
}
The data that gets fetched is legit, but the log line always prints "GOT COLORS FOR colorless" the last of the keys.
cardColoursfunction is async. The callback is being invoked after the loop finished.