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

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -