我需要在客户端获取服务器上的信息。因此,在服务器端,当客户端首次连接时,会得到以下内容:
socket.on('adduser', function(username){
// misc code, where i set num_player and whatnot
socket.emit('confirmauth', socket.id, socket.num_player, function(data){
console.log(data)
});
// code
}
在客户端,我得到了这个:
var current_player;
socket.on('confirmauth', function(id, username, num, callback) {
current_player = new Player(username,id, num);
console.log(current_player.id); // works
console.log(current_player.num); //works
callback('ok i got it');
});
console.log(current_player.id); //undefined
console.log(current_player.num); //undefined
我的问题是,在socket.on之外,player未定义。似乎javascript在继续执行之前不等待socket.on检索数据。
我尝试将socket.on包装在$.when done中,但它不起作用。我尝试过回调,但我认为我可能没有很好地理解它应该如何工作。所以如果你们中的任何人愿意帮助我,我将非常感激。
谢谢你们的答复。
//...
表示)都需要移动到回调函数内部。如果player
是某种全局变量,你也可以从回调函数内初始化它,但是你需要确保在初始化之后再开始运行使用全局变量的代码:getPlayer(function(p){ player = p; startGame(); })
- hugomg