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


this question has answer here:

i make request url, , try use response further, in function, 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 run script

node ./test.js  

i

'undefined' console message 

i don`t know may come from, new node.js, javascript

var test = callback(getaddress); 

is asynchronous function

console.dir(test); 

won't wait finish before executing, hence getting undefined. make work have 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); 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -