Below is the code for CardLoader, which I am using to get a json file containing information about the playing cards I want to use. However, after I create a CardLoader in my client code, and then call the getGameCards() function, I am receiving an empty map. I have run through the debugger and the issue lies with the loadCards method. Since this is completing asynchronously, pickGameCards() is executed before the loadCards function has completed. I am unsure about how I should handle this? What techniques are there for waiting until completion?
function CardLoader(){
var cards = this.loadCards();
this.gameCards = this.pickGameCards(cards);
}
CardLoader.prototype.pickGameCards = function(cards){
var random;
var gameCards = {};
var length = cards.length - 1;
for(var i = length; i > length - 7; i--){
gameCards[cards[i].name] = cards.splice(i, 1);
}
for(var i = 0 ; i < 10; i++){
random = Math.floor((Math.random() * cards.length));
gameCards[cards[random].name] = cards.splice(random, 1);
}
return gameCards;
}
CardLoader.prototype.loadCards = function(){
var allCards = [];
$.getJSON("cards.json", function(data){
$.each(data.cards, function(index, value){
allCards[index] = data.cards[index];
});
return allCards;
});
}
CardLoader.prototype.getGameCards = function(){
return gameCards;
}