javascriptnode.jsrequestnpm-request

node setting this.var inside class async method


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?


Solution

  • 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");
    });