0

i am trying to get a simple value from my node server like so:

getNodeServerValue = function()      {
    return io.socket.emit('server-Query', 
         function(data) {
               console.log('data is now: ' + data);  // works fine!
               return (data);
         }
   );
}

and i wish to be able retrieve the value like this:

var myReturnedValue = getNodeServerValue();

but returnedValue contains the function itself, and not the value being returned. and getNodeServerValue()() did not work either.

i have attempted returning a variable, setTimeout, clearTimeout, etc. with no success because of the async nature of jScript.

this example is loosely based on the "Sending and getting data (acknowledgements" example in the socket.io docs.

looking here and here didn't help me since my requirements are double nested, and also i need to name the getNodeServerValue with a variable.

i am sure this is an easy question, so please dont down-vote me without an explanation.

thank you very much.

Community
  • 1
  • 1
edwardsmarkf
  • 1,387
  • 2
  • 16
  • 31
  • 2
    you can´t return the data because it will not be available by the time your function returns. You need to use callbacks: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – juvian May 26 '16 at 18:10
  • 1
    You should use promises. – William B May 26 '16 at 18:38

1 Answers1

1

You can use a promise library, or if in Node they are supported natively

io.getNodeServerValue = new Promise(function (resolve, reject) {
  io.socket.emit('server-Query', 
         function(data) {
               resolve(data);
         }
   );
});

use it like so:

io.getNodeServerValue.then(function (data) {
  // data is here!
});
William B
  • 1,411
  • 8
  • 10
  • your suggested solution will "initialize" when the node client first connects, but the function does not execute after that. is there a way to make sure that the function runs every time, and not just when the socket connects? – edwardsmarkf May 26 '16 at 22:33