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
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With