0

I have tried now to get a variable out of a socket.on(); but can't get it out as it says it is an undefined variable.

Here is the code bit that doesn't work:

 io.on('connection', function(socket){
    socket.join("0");
    socket.on("chatroom",function(chat){
        socket.join(chat);
        if(chat != "0"){
        console.log("A user joined chatroom: " + chat);
        }
        var chatroom = chat;
    });

}); 

var chatroom = chatroom;

As you see it is the variable above that get's a value of undefined even if it has a value of 2 in the io.on fuction. Any ideas how to get it out?

Excuse me for my noobish codes (only 3 days experience in node.js)

  • 1
    It sounds like you maybe need to read this: [How to return a value from an asynchronous operation](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). The structure of what you're trying to do is just wrong. Async results must be consumed IN the async response, not elsewhere. – jfriend00 Dec 16 '15 at 03:17

1 Answers1

0

I think the external chatroom variable is eclipsed by the internal one. Try:

var chatroom;
io.on('connection', function(socket) {
    socket.join("0");
    socket.on("chatroom", function(chat) {
        socket.join(chat);
        if(chat != "0") {
            console.log("A user joined chatroom: " + chat);
        }
        chatroom = chat;
    });    
}); 

Also, you have to understand, that because the code is asynchronous, the last line of your code will be executed before the code inside of the io.on('connection', ...)

Filip Spiridonov
  • 34,332
  • 4
  • 27
  • 30