1

Basically, I am having an issue when I make an instance of this class that the .token property is not being initialized in time to use when the instance is being called.

I have converted the function into an async function that returns a promise and resolves the api token. This functionality works.

When I go over to my controller and when i let t = new API and immediately console.log(t.token); it prints undefined. When I do a set timeout for a few seconds and then print t.token, I get the token.

I need this to continue executing once the instance has fully be created. How can I do this?

Here is the constructor and corresponding function that fires the request to get the token / pulls it from cache.

constructor() {
        // All this should go to .env
        this.api_key = 'key';
        this.api_url = 'https://some.api.com/v2';
        this.api_clientId = 'id';
        this.api_clientSecret = 'secret';
        //this.token = this.getAccessToken();
        //console.log(this.getAccessToken());
        this.getAccessToken().then((token)=>{
                console.log('In Initialization'+ token);
                this.token = token;
            });
    }

    private async getAccessToken(): Promise<any> {
        let token = new Promise(resolve => {
            myCache.get('apiKey', (err, result)=>{
                if(err) throw err;
                if(result == undefined){
                    request('https://some.api.com/oauth/v2/token',{
                        method:'POST',
                        form: {
                            grant_type: 'client_credentials',
                            client_id: this.api_clientId,
                            client_secret: this.api_clientSecret
                        }
                    }, (err, res, body) => {
                        if(err) throw err;
                        myCache.set('apiKey', body, (err2: any, suc: any)=>{
                            if (err2) throw err2;
                            resolve(body);
                        });
                    });
                } else {
                    resolve(result);
                }
            });
        });
        return token;
    }

Here is where the instance is created:

export const getSomething = (req: Request, res: Response)=>{
    let t = new API;
    setTimeout(()=>console.log('In Timeout:   ' + t.token), 1000);
    console.log(t.token);
    return res.send({token: t.token});
}

The JSON response is does not contain the token when the response is sent both when it is pulling from cache and hard requesting on the api -- but prints after the setTimeout.

  • 1
    This should help: [Is it bad practice to have a constructor function return a Promise?](https://stackoverflow.com/q/24398699/218196) ... the top answer explains how you should structure your code instead. – Felix Kling Feb 12 '19 at 23:05

0 Answers0