简体   繁体   中英

How to save value from a function inside socket.on to a global variable?

This is probably very simple, but I am fairly new to programming in Javascript and using Socket IO.

When I want to give a global variable a value from inside a function the process is fairly simple:

var j;

function a(){
j=2;

}
a();
//j is now 2

My issue now is, I have a method called socket.on, which has a function inside it, like this:

var j;

socket.on('news', function (p) {
j=p; 
//in here, j is equal to p
});
//in here, j is NOT p, it is undefined.

Now, in this case I want my global variable j to have the value of p, but when I print j outside of the function, it is undefined. I assume this is because I need something like a(); outside the function like in the first example. How can I do this in this case?

Thank you so much.

The second parameter of socket.on is a so called callback function, a very common pattern in javascript. In your example you are listening to the 'new' event. When this event occurs, the callback is fired with the argument p . Of course this argument is only available inside the callback function itself.

To be clear: You do not call the function in the second example directly. It is called once the 'news' event occurs.

The callback pattern is very handy, because it allows you to write non blocking code. While you are waiting for the 'news' event to occur, any code after your socket.on call is being executed normally. This is the reason why you cannot access p outside the callback: You don't know at what point in time the callback will be called.

I suppose you read a little more about Javascript's event loop or functions and their scope .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM