positron
positron

Reputation: 3693

Getting TypeError when getting instance of AsyncLocalStorage

I want to access instance of AsyncLocalStorage in a global way in different modules of my Express application. I've created Singleton class that holds instance of ALS (may be there is another way to do it and this is overkill?)

index.ts

const { AsyncLocalStorage } = require('async_hooks')

export class Singelton {    
  private static instance: Singelton;
  private asyncLocalStorage: typeof AsyncLocalStorage;

  private constructor(){
    this.asyncLocalStorage =  new AsyncLocalStorage();
  }

  public static getInstance(): Singelton {
    if(!Singelton.instance) {
        Singelton.instance = new Singelton();
    }
    return this.instance;
  }

  public getAsyncLocalStorage()  {
    return this.asyncLocalStorage;
  }
}

other.js

    const als = Singelton.getInstance().getAsyncLocalStorage();
    let trace_id = als.getStore().get("userName")

At line als.getStore().get("userName"), I am getting error

TypeError: Cannot read properties of undefined (reading 'get')

What is the cause of this error? is als not being instantiated in Singleton?

Upvotes: 0

Views: 856

Answers (1)

Prateek Jha
Prateek Jha

Reputation: 1

Typescript still does not know what methods are available to the als singleton instance. You can create an interface and specify what methods and attributes will be available to the singleton instance.

Upvotes: 0

Related Questions