Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript class property returning undefined despite assignment

I cant seem to re-define the authToken property at all, and outside the scope of the constructor, it just returns undefined no matter what, whether i’m referencing it in File 1 or File 2. Below is some example code.

File 1:

class Clazz {
    authToken;

    constructor() {
        getAuthToken().then((token) => {
            this.authToken = token;
        });
    }
}

const getAuthToken = () => {
    return new Promise((resolve, reject) => {
        adalcontext.acquireTokenWithClientCredentials(resourceapi, clientId, clientSecret, (error, tokenResponse) => {
            if (error) {
                reject(new Error(`Failed to authenticate: ${error.message}`));
            } else {
                resolve(tokenResponse.accessToken);
            }
        });
    });
};

File 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const clazz = new Clazz();

console.log(clazz.authToken) // => returns undefined

I have tried many different things but none seem to be working. Any help would be appreciated. Thanks.

>Solution :

You try to access authToken before it’s assigned in an async operation. Make authToken a promise and wait it fullfilled:

class Clazz {
    authToken;

    constructor() {
        this.authToken = getAuthToken();
    }
}

...

// in a module or async function:

const clazz = new Clazz();

console.log(await clazz.authToken)

Another option would be an async factory:

class Clazz {

    static async create(){
        return new Clazz(await getAuthToken());
    }   

    authToken;

    constructor(authToken) {
        if(!authToken){
            throw new Error('Cannot create Clazz without authToken');
        }
        this.authToken = authToken;
    }
}

...

// in a module or async function:

const clazz = await Clazz.create();

console.log(clazz.authToken)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading