0

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

  1. returning the JSON object to a variable from the async callback in get_json
  2. Use this code base in a JS file and reference it in a web application.

Thanks in advance.

  • You seem to be using some non-standard javascript library. Please mention this and add relevant tags. – petr Aug 28 '15 at 07:52
  • possible duplicate of [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Hacketo Aug 28 '15 at 07:54

0 Answers0