0

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?

1 Answers1

1

Request can't return Promises on its own, but you can wrap it inside a Promise to solve this without a package like request-promise-native

async getVar() {
    return new Promise((resolve, reject) => {
      request.get(
        url,
        (err, resp, body) => {
          if (!err) {
            var res = JSON.parse(body);
            this.var = res.var;
            console.log(res.var, "resVar");
            resolve(true);
          } else {
            console.log(err);
            reject(err);
          }
        }
      );
    });
  }

And for example in your function:

app.get("/", async (req, res) => {
  const TestInstance = new Test();

  await TestInstance.getVar();

  console.log(TestInstance.getVarResult(), "It Works");
});
  • 1
    This won't help with the basic issue, which is that the HTTP request is **asynchronous**. – Pointy Feb 16 '19 at 14:39
  • Ok I've edited my answer, I had the same problem with request because I'm used to Axios promises, hope it'll help you – Miguel Castillo Feb 16 '19 at 15:12
  • @MiguelCastillo thank you. can I pass the var in the resolve? – JoaoFilipeClementeMartins Feb 16 '19 at 16:41
  • @JoaoFilipeClementeMartins of course, you even can return the whole result and getting what you want with destructuring or the promise chain. You can read more about the Promises here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises – Miguel Castillo Feb 18 '19 at 21:39