My code block goes like this :
var http = require("http");
function get_json(url,callback) {
var response = '';
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
response = JSON.parse(body);
callback(response);
});
});
}
// -----------the url---v ------------the callback---v
var mydata = get_json("http://alfreddelivery.cloudapp.net/api/questionnaire/",function fn(item){
console.log(item);
});
I would like to catch the output of get_json function and then assign it to a variable for future options. I tried, var mydata to access the JSON object parsed, but, since the program execution flow hits the mydata variable first, it returns, undefined value for the variable. I have reused this code from stack overflow itself. Please help me for
- returning the JSON object to a variable from the async callback in get_json
- Use this code base in a JS file and reference it in a web application.
Thanks in advance.