async/await in javascript class method with htpps call inside

Viewed 134

I tried to make an https call and return the body containing the data, but when I tried to print it in the console it returned undefined so I used the "promises".

const https = require('https');
const baseUri = "https://apiv2.gofile.io/"


class apiGofile {

    constructor(email,apikey) {
        this.email=email;
        this.apikey=apikey;
    }

    getBestServer() {
        return new Promise((resolve,reject)=>{
            https.get(baseUri + "getServer", (res) => {
            
                let body="";
                
                res.on("data", (data) => {
                    body += data;
                });
                
                res.on("end", () => {
                    body = JSON.parse(body);
                    
                    resolve(body.data.server);
                });
    
                res.on("error",(e)=>{
                    reject(e);
                });
            });
        });
       
    };
}

let a = new apiGofile("a","b");


a.getBestServer()
.then(
    response => console.log(response),
    error => console.log(error)
); 

is there any way to use await and async in my code?

1 Answers

You can move the following code into an asynchronous main function then call that:

async function main() {
    const a = new apiGoFile("a", "b");
    // await the promise instead of using .then
    const response = await a.getBestServer();
    console.log(response);
    // you can now use response here
}

// make sure to call the function
main();

You can read more about async/await here.

You can also make class methods async:

class Foo {
    async myMethod() {
        const a = new apiGoFile("a", "b");
        const response = await a.getBestServer();
        console.log(response);
    }
}
Related