Async Components
Sometimes the application start has to be delayed until some asynchronous tasks will be finished, for example until the connection with the database will be established. That's why Nest provides a way to create async components.
To create an async component, we're using the useFactory. The factory must return Promise or just be marked as an async function.
{
provide: 'AsyncDbConnection',
useFactory: async () => {
const connection = await createConnection(options);
return connection;
},
},
Hint Read more about custom components here.
These asynchronous components might be simply injected to other components by the token (in this case, by AsyncDbConnection token).
Each component, which depends on the async components will be instantiated when the async component would be already resolved.
The above example is for demonstration purposes. If you're looking for more detailed one, see here.