简体   繁体   中英

Get a value out of a socket.io function?

I am trying to create a function that will return the value of answer. However I am having trouble in getting this value out.

What it is currently doing is getting some data from the server and storing that in data. However I am wanting to make this value easier to get to as to not have to constantly wrap my content within the serverAnswer function. Is this possible to do?

 var serverAnswer = (function() { var answer; socket.on("server answer", function(data){ answer = data.year; }); return function() { alert(answer); }; }()); serverAnswer(); console.log(answer); 

You can't exactly do that in a synchronous way. However you can create a function where you want that answer value and call that from socket callback. or even socket callback can be your function where you want to utilize answer value.

function doit(answer){
    // do something with answer
}

You can do this

socket.on("server answer", function(data){
    answer = data.year;
    doit(answer);
});

Or this

socket.on("server answer", doit);

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