1

I'm trying to get a JSON response via the request method and return the output so that i can store it in a variable when the function is called. when i log the response within the request method, it works fine. However when i return the output, it doesn't return.

 var getAPIresponse = function(url) {
    var request = require('request');
    request(url, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            console.log(body); // WORKS PERFECTLY
            return body;      // I Believe the issue is here
        } else {
            console.log("Error: "+ error);
        }
    });
};

router.get('/', function (req, res) {
    var poolList =  getAPIresponse("www.addAURL");

    console.log(poolList); // DOESN'T WORK. REPORTS AS UNDEFINED
    res.render('index', model); // THIS IS JUST SAYS HELLO WORLD
});
the_lost_one
  • 127
  • 10
  • 1
    [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) You can't. With `request()` being asynchronous, `getAPIresponse()` actually completes its execution, returning `undefined` to `poolList`, before the callback is invoked and `body` is defined. – Jonathan Lonowski Feb 25 '16 at 05:27

1 Answers1

1

What your method actually does is run the following two lines

var request = require('request');
request(url, function(error, response, body) {

...and then fall out of the function right away at which point your calling code gets undefined back. The callback isn't called until the request is done, which may be much later.

To make it work, your function needs a callback too that is called when the function is actually complete, something like;

var getAPIresponse = function(url, cb) {
    var request = require('request');
    request(url, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            console.log(body); // WORKS PERFECTLY
        } else {
            console.log("Error: "+ error);
        }
        cb(error, body);
    });
};

router.get('/', function (req, res) {

    var poolList =  getAPIresponse("www.addAURL", function(err, poolList) {

        // This is run in a callback once the request is done.    
        console.log(poolList);
        res.render('index', model);

    });
});

Another way would be to use promises which can clean up the code somewhat when the number of callbacks is getting out of hand.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294