Advanced Usage
In this section, we’ll explore more advanced features of the library, including managing dependencies between containers and handling asynchronous tasks. These features allow you to build more complex container configurations and manage the execution flow in larger applications.
Example 1: Using Dependencies
Here’s an example that demonstrates how to set up containers with dependencies. In this example, we create two containers: userContainer
, which fetches user data, and accountsContainer
, which depends on userContainer
to retrieve the user’s accounts.
Expected Result
In this example, you should see the following output in the console:
This output confirms that accountsContainer
started only after userContainer
initialized and provided the necessary userId
.
Example 2: Handling Asynchronous Tasks
You can also manage asynchronous operations within containers. Here’s an example where userContainer
performs an asynchronous data fetch for user information, and accountsContainer
depends on this data to load user accounts.
Why await compose.up
?
In this example, we use await
with compose.up
to ensure that all containers complete their asynchronous operations before continuing. Since compose.up
returns a promise, awaiting it allows you to know when all containers have finished their startup processes.
The promise returned by compose.up
provides an object with the following structure:
Expected Result
When you run this code, you should see output similar to:
This confirms that accountsContainer
waits for userContainer
to complete and uses the fetched user data to load the accounts.
Summary
In Advanced Usage, we explored how to create containers with dependencies and perform asynchronous operations. These features provide more flexibility and control over container initialization, making it easier to manage complex configurations in larger applications.