0

I am having issues getting the value returned from a function nested in a function from another function. The code is pretty complicated, but i mocked up something here:

var request = require('request');
var _url = 'test.com/data/data.json';

function getValue() {
  var val = 0;
  return callFromURL(function(result){
    if(result) {
      // Do stuff...

      console.log(result); //Returns a value
      return result;
    }
  })
}

function callFromURL(callback) {
  request(_url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var service = JSON.parse(body);
            return callback(service);
        } else {
            log.error(error);
            return callback(null);
        }
    });
}


function test() {
  getValue(); //returns undefined
}

When i step through using a debugger or console.log statements I see that the inner return in the callback passed to callFromURL is not undefined, but the result of return callbackFromURL is undefined. How can I correctly return result from the getValue() function in this example?

Soatl
  • 10,224
  • 28
  • 95
  • 153
  • 2
    See classic async question http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – elclanrs Mar 07 '16 at 16:34
  • yeah you can't do that. – Kevin B Mar 07 '16 at 16:35
  • Your saying it isn't possible to get result to return in the main function? I have a hard time believing that – Soatl Mar 07 '16 at 16:37
  • Yup, not possible. Once you go async there is no way out. The approach is to nest callbacks or pass promises around. It was never possible for a function to return to the outer function. – elclanrs Mar 07 '16 at 16:38
  • What you're asking for is similar to asking to be able to return a value from an ajax call to the function that initiated the ajax call; it simply isn't possible unless you make the ajax request synchronous. – Kevin B Mar 07 '16 at 16:40
  • @PepperedLemons: The function returns before the callback is executed asynchronously. Unless you invent time travel, it's impossible to get a value from the callback as the return value of the function. – Bergi Mar 07 '16 at 16:50
  • Makes sense after reading the other post. Thanks for the help everyone! – Soatl Mar 07 '16 at 18:03

0 Answers0