Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js request object- return response body for further operation [duplicate]

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

like image 497
Glenn Dekhayser Avatar asked Feb 01 '15 22:02

Glenn Dekhayser


1 Answers

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); 
  }
});
like image 53
Ben Avatar answered Nov 07 '22 02:11

Ben