Search code examples
javascriptclasspromiseconstructorproperties

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:

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)