JavaScript、node.js 在继续之前等待 socket.on 响应

标签 javascript node.js sockets wait

我需要在客户端从服务器获取信息。 所以在服务器端,当客户端第一次连接时我得到了这个:

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

我的问题是在套接字之外,播放器未定义。看来 javascript 不会等待我的套接字在继续之前检索数据。

完成后,我尝试将 socket.on 包装在 $. 中,但它不起作用。我尝试进行回调,但我想我可能不太了解它应该如何工作。所以如果你们中有人愿意帮助我,我将不胜感激

感谢您的回答。

最佳答案

如果您将 current_player 变量放在 on 回调之外以试图返回它,另一种方法是创建您自己的函数接收回调

function getPlayer(onDone){
    socket.on('confirmauth', function(id, username, num, callback) {
        var current_player = new Player(username,id, num);
        onDone(current_player);
    });
}

而不是做

var player = getPlayer();
//...

你会

getPlayer(function(player){ 
    //...
});

“回调性”在 Javascript 中有点传染性,这有点糟糕,但在每个人开始使用生成器之前,生活就是这样。

关于JavaScript、node.js 在继续之前等待 socket.on 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23815500/

相关文章:

c - 如何在混杂模式下打开原始 UDP 套接字?

javascript - AngularJs 使用 bool 运算符一次性绑定(bind)和值的顺序

node.js - 如何在 Amazon Cognito 中高效获取大量用户

javascript - 在javascript或jquery中单独调用特定函数

javascript - 如何将 mocha 测试与 async.series 一起使用

javascript - NodeJS 在运行时添加/删除/重新加载需要无需重新启动服务器(也不需要 nodemon)

java - SSL 不适用于 Android 2.2(仅适用于 2.3)

python - 更大的应用程序如何处理潜在的(网络)套接字端口冲突?

javascript - 调用函数时如何使用数组对函数进行排队

javascript - 编译两个页脚相关的javascript