14

There's probably an easy answer for this, but I'm trying to get the body of the response back and returned to another function. It's certainly a scope problem.

Here's my code, any ideas would be most appreciated:

var request = require("request");
var myJSON = require("JSON");

function getMyBody(url) {
    var myBody;
    request({
    url: url,
    json: true
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
        myBody = body;
    }
 });

return(JSON.parse(myBody));

}

js_traverse(getMyBody(url));

Thanks

Glenn

Glenn Dekhayser
  • 145
  • 1
  • 1
  • 7
  • Looks like the everyday asynchronous question. `getMyBody` should take a callback, or return a promise. – elclanrs Feb 01 '15 at 22:51
  • See if this helps http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Feb 01 '15 at 22:56

1 Answers1

17

The statement:

return(JSON.parse(myBody));

Get executed before the ajax call returns you the body. You need to pass in the callback to getMyBody() to do something with what the body of request() returns:

var request = require("request");
var myJSON = require("JSON");

function getMyBody(url, callback) {
  request({
    url: url,
    json: true
  }, function (error, response, body) {
    if (error || response.statusCode !== 200) {
      return callback(error || {statusCode: response.statusCode});
    }
    callback(null, JSON.parse(body));  
  });
}

getMyBody(url, function(err, body) {
  if (err) {
    console.log(err);
  } else {
    js_traverse(body); 
  }
});
Ben
  • 5,024
  • 2
  • 18
  • 23
  • no need to write the return in `return callback(error)` and no need to do `JSON.parse(body)` on success while you said `json: true` ^^ – NoxFly Sep 26 '19 at 17:38
  • @NoxFly Without the return, the code will follow through and executes another callback statement below – Ben Sep 27 '19 at 16:50
  • @NoxFly, to address the second part of your comment... You are right that JSON.parse() is not needed but the point here to answer the question which is how to return the data in an async call and it was chosen to leave the rest of the code as is. – Ben Sep 27 '19 at 17:47