下面是CardLoader的代码,我用它来获取一个json文件,其中包含有关我想要使用的扑克牌的信息。但是,在我的客户端代码中创建CardLoader,然后调用getGameCards()函数后,我收到一个空映射。我已经完成了调试器,问题在于loadCards方法。由于这是异步完成的,因此在loadCards函数完成之前执行pickGameCards()。我不确定我应该如何处理这件事?有什么技术可以等到完成?
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;
}
答案 0 :(得分:0)
我建议使用promises而不是回调,因为与同步相比,promises在代码中的变化很小 使用回调时,您需要重新考虑所有内容。
我必须在代码中只改变4行。
function CardLoader(){
var cards = this.loadCards();
this.gameCards = this.pickGameCards(cards);
}
CardLoader.prototype.pickGameCards = function(cards) {
return cards.then(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(){
return $.getJSON("cards.json").then(function(data){
var allCards = [];
$.each(data.cards, function(index, value){
allCards[index] = data.cards[index];
});
return allCards;
});
}
CardLoader.prototype.getGameCards = function() {
return this.gameCards;
}
在客户代码中:
$("#get-cards-button").click(function() {
someCardLoader.getGameCards().then(function(cards) {
});
});
假设至少jQuery 1.8,在早期的jQuery中你需要使用.pipe
而不是.then