edwardsmarkf edwardsmarkf - 6 months ago 19
Node.js Question

returning value from double-nested function

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.

Answer

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!
});
Comments