2

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
    Make your life easier and use libraries like [node-fetch](https://www.npmjs.com/package/node-fetch) or Axios. You can just `await fetch(url)` or `await axios.get(url)`. – Jeremy Thille Dec 02 '20 at 14:08
  • 1
    console.log() => //returns `undefined` but it prints properly to me: `srv-store1` – sonkatamas Dec 02 '20 at 14:09
  • it works with "promise" but I wanted to use async and await to improve calling out of class – 404ProgramNotFound Dec 02 '20 at 14:15
  • "*is there any way to use await and async in my code?*" - yes, you can replace the `then` call with an `await`. Have you tried? – Bergi Dec 02 '20 at 15:39
  • @Bergi i used it and it worked but i ment using it in class method anyway i used a simple callback function and it cleaned up my call in main code – 404ProgramNotFound Dec 02 '20 at 15:50
  • 1
    @404ProgramNotFound No, [you can't use `async`/`await` to promisify](https://stackoverflow.com/q/45788934/1048572) the https call in `getBestServer`. – Bergi Dec 02 '20 at 15:52

1 Answers1

1

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);
    }
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55