JavaScript,node.js 在继续之前等待 socket.on 响应 [英] JavaScript, node.js wait for socket.on response before continuing

查看:42
本文介绍了JavaScript,node.js 在继续之前等待 socket.on 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to get information from the server on the client side. So on the server side I got this when a client first connect:

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
}

在客户端,我得到了这个:

and on the client side I got this:

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 似乎不会等待我的套接字打开来检索数据.

my problem is that outside of the socket on, the player is not defined. It seems that javascript doesn't wait for my socket on to retrieve data before carrying on.

我尝试将 socket.on 包装在 $.when 中,但它不起作用.我试图做一个回调,但我想我可能不太了解它应该如何工作.所以如果你们中的一个愿意帮助我,我将不胜感激

I tried to wrap socket.on in a $.when done, but it doesn't work. I tried to do a callback, but I think I may not have understood very well how it is supposed to work. So if one of you is willing to help me, I will be grateful

感谢您的回答.

推荐答案

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

If you are putting the current_player variable outside of the on callback in an attempt to return it, the alternative is to make your own function receive a callback

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 中有点传染性,这有点糟糕,但在每个人都开始使用生成器之前,这就是生活.


It kind of sucks that the "callbackyness" is a bit infectious in Javascript but such is life until everyone starts using Generators instead.

这篇关于JavaScript,node.js 在继续之前等待 socket.on 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆