Home > Enterprise >  Wait for async initialisation of a service?
Wait for async initialisation of a service?

Time:01-18

@Injectable()
export class MyService {
  ...
  constructor(@Inject('CONFIG') private config:ConfigOptions){
    this.connection= // await initConnection(config); <-- this returns a promise! How to await this?
  }
   
  send(payload:string){
    this.connection.send(payload)
  }
}

How to await the async call to initConnection() to ensure the service is initialised before being used?

CodePudding user response:

Constructors cannot have asynchronous code, that's just how JavaScript is. What you can do instead is either make use of the onModuleInit hook and await the connection there, or take the CONFIG provider you have and make a CONNECTION provider via custom provider with useFactory which can have an await. Something like

{
  provide: 'CONNECTION',
  inject: ['CONFIG'],
  useFactory: async (config: ConfigOptions) => {
    return await initConnection(config);
  }
}
  • Related