Zekfad
Zekfad

Reputation: 179

await http request response in constructor

I have a class, how I can create await for key value, that should be requested from http request in another method?

I don't know how to correct use await in this situation.

Here code, it returns only undefined:

class MyClass {
    constructor(key = null) {
        if (!!key)
            this.key = key;
        else
            (async () => { this.key = await this.getKey(); })(); 
    }
    getKey(input) {
        return new Promise((resolve, reject) => {
            let options,
                request,
                data = '';

            try {
                options = {
                    host: '...',
                    port: '80',
                    path: '/',
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                };
                request = http.request(options, (response) => {
                    response.setEncoding('utf8');
                    response.on('data', (chunk) => {
                        data += chunk.toString();
                    });
                    response.on('end', () => {
                        resolve(new RegExp('<div id="...".*>(.*)<\/div>', 'g').exec(data)[1]);
                    });
                });
                request.end();
            } catch (error) {
                reject(error);
            }
        });
    }
}

Upvotes: 2

Views: 2034

Answers (2)

Kokodoko
Kokodoko

Reputation: 28138

Perhaps I'm as confused about async await as you are, but it doesn't really seem necessary in this scenario.

class MyClass {

    initKey() {
        this.getKey().then(d => { this.key = d })
    }

    getKey(){
        return new Promise((resolve, reject) => {
            resolve("the promised value")
        })
    }
}

let t = new MyClass()
t.initKey()

Upvotes: 2

LMokrane
LMokrane

Reputation: 826

a better usage would be to use await for the var you'll put in parameter :

let key = await getKey();
let myClass = new MyClass(key);

Upvotes: 2

Related Questions