factor_za factor_za - 3 months ago 5x
Javascript Question

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() {



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;

Or this

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