I am creating a node js class to use in my app that consumes a restful API. To hit that API I am using the node pckg request.
var request = require('request');
class Test{
constructor(){
this.var = {};
}
async getVar(){
request.get(url, function(err, resp, body) {
if (!err) {
var res = JSON.parse(body);
this.var = res.var;
console.log(res.var);
} else {
console.log(err);
}
});
}
getVarResult(){
return this.var;
}
}
Inside the get request I can print the variable in the console.log and the result shows fine. But after the getVar()
method is executed if I call the getVarResult()
it keeps returning undefined
or empty
.
I understand that what I am probably doing is set this in the context of the rest and not reassigning to the this.var
on the constructor class.
How can I do what I am trying to do here? can I set a var inside the get request method that sets it at the class level and is accessible through a getter type method?