NestJS Logo

Asynchronous providers

Sometimes the application start should be delayed until one or more asynchronous tasks complete. For example, you may not want to start accepting requests until the connection to the database has been established. Asynchronous providers let you do this.

To create one, use async/await with the useFactory syntax. The factory returns a Promise, and the factory function can await asynchronous tasks. Nest awaits resolution of the promise before instantiating any class that depends on (injects) such a provider.


{
  provide: 'ASYNC_CONNECTION',
  useFactory: async () => {
    const connection = await createConnection(options);
    return connection;
  },
}
Hint Learn more about the custom provider syntax in the custom providers chapter.

Injection#

Asynchronous providers are injected into other components by their tokens, like any other provider. In the example above, you would use @Inject('ASYNC_CONNECTION').

Edit on GitHub

Support us

Nest is an MIT-licensed open source project. It can grow thanks to the support of these awesome people. If you'd like to join them, please read more here.

Principal Sponsors

SerpApi LogoTrilon LogoMojam Logo

Sponsors / Partners

Become a sponsor