0

I'm having some troubles using a nodejs function. All i want to do is get the return value. When i look at my consolelog, i can see 'Undefined'.

I know that this is because callbacks does not end before console.log is executed but i dont have a clue that how to resolve this problem.

var info = api.getBridge();
console.log(info)

api.getBridge = function () {

   var hue = require("node-hue-api");
   var resultado;

   hue.nupnpSearch(function (err, result) {
      if (err) throw err;
      return result;
   });
}
Knut Holm
  • 3,988
  • 4
  • 32
  • 54
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – JJJ Apr 29 '15 at 09:45
  • you can't return a value from an async method... you need to use callbacks - http://jsfiddle.net/arunpjohny/uft4jfdg/1/ – Arun P Johny Apr 29 '15 at 09:46

2 Answers2

0

You could try do do the console.log inside the callback:

var info = api.getBridge();

But inside your callback:

var callbackvalue = hue.nupnpSearch(function(err, result) {
    if (err) 
        throw err;
    return result;
});
console.log(callbackvalue);

Well, now you know what your function returns. To use this "returnvalue" further you just have to call the code that is processing your results and call it with the according value:

var thisProcessesYourResults = function(someValueToProcess){...}

And again, inside your callback:

thisProcessesYourResults(callbackvalue);

When working asynchronously, you just can not return a value to the original calling context. The resulting code (if it gets complex enough) can be misleading or confusing at best. A way to deal with this are promises.

Mathias Vonende
  • 1,400
  • 1
  • 18
  • 28
0

I would try to avoid nested callbacks and just do something like this:

// this code will execute synchronously
var hue = require("node-hue-api");
var resultado;

// this code will execute asynchronously
hue.nupnpSearch(function(err, result) {
    if (err) throw err;
    var info = response;
    console.log(info);
    //all further operations on the returned values should happen here
});
deowk
  • 4,280
  • 1
  • 25
  • 34