Search code examples
javascriptnode.jscallbackget-request

Can`t use the response from a get request using callback function


I make a get request from a url, and I try to use the response further, in another function, so this is what I tried first.

var request = require("request");

function getJSON(getAddress) {
    request.get({
        url: getAddress,
        json: true,
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            return body;
        }
     })
 }

function showJSON(getAddress, callback) {
    var test = callback(getAddress);
    console.dir(test);
}

showJSON('http://api.open-notify.org/astros.json', getJSON);

yet, when i run my script

node ./test.js 

I get

'undefined' as a console message

I don`t know where this may come from, as I am new to node.js, javascript


Solution

  • var test = callback(getAddress);
    

    is an asynchronous function

    console.dir(test);
    

    won't wait for it to finish before executing, hence you are getting undefined. to make it work you would have to do

    var request = require("request");
    
    function getJSON(getAddress, callback) {
        request.get({
            url: getAddress,
            json: true,
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                callback(body);
            }
         })
     }
    
    function showJSON(getAddress, callback) {
        callback(getAddress, function(test){
            console.dir(test);
        });
    }
    
    showJSON('http://api.open-notify.org/astros.json', getJSON);