I'm not very experienced in web things, and I'm trying to make a simple api call within a class. I'm running into the very classic callback problem that new people face, and while there are tons of examples of how to handle this logic, I'm having a really hard time implementing it within a class. I'm using request. Obviously nothing below works, especially in relation to myBody
, but I added it to show how I logically thought about it before worrying about asynchronous calls.
const request = require('request);
class GetData{
constructor(){
this.getData();
}
reallyGetData(){
var myData = this.getdata;
return myData;
}
getData(){
//var myBody;
request({'url':`https://somewebsite.com/things.json`, 'json': true }, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
// Successfully returns body as expected
console.log("From inside getData: " + body);
//myBody = body;
});
//return myBody;
}
}
The most useful link I've found explaining how I get the body outside of the getData scope is this one.
However, I'm pretty new to node (and javascript all together), and I can't seem to get the syntax for adding the callback function. Everything I try from examples is invalid syntax, so when I try adding a callback function similar to:
getData(function(result) {
console.log(result);
}
I don't know how to implement this logic within a class.