I am learning Node.js and I have searched all over the place to understand how to handle this bit of code. I am writing a module that communicates with an open API. It basically requests for a JSON and returns it to the caller that requires this moule.
This is inside a module.exports function:
// prep URL
var request = require('request');
request({
url: requestURL,
json: true
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // need to return this data
}
});
Instead of console.log(body), I want to return the body back from this function. But because the callback function is asynchronous, it does not work.
I can make a callback function, but I want to return the data from this module.exports function, so that would be weird. I could put this request code in a helper function instead of the module.exports function, but I cannot figure out how to return the data back anyway.
Should I organize my code in some other way?
I solved my problem by adding a callback function to my API. This way, the parent module can choose what to do with the retrieved JSON data.