Dealing with Asynchronously Initialized Components

Learn how to initialize asynchronous components in JavaScript applications.

One of the reasons for the existence of synchronous APIs in the Node.js core modules and many npm packages is that they’re handy to use for implementing initialization tasks. For simple programs, using synchronous APIs at initialization time can streamline things a lot, and the drawbacks associated with their use remain contained because they’re used only once, which is when the program or a particular component is initialized.

Unfortunately, this isn’t always possible. A synchronous API might not always be available, especially for components using the network during their initialization phase to, for example, perform handshake protocols or retrieve configuration parameters. This is the case for many database drivers and clients for middleware systems such as message queues.

The issue with asynchronously initialized components

Let’s consider an example where a module called db is used to interact with a remote database. The db module will accept API requests only after the connection and handshake with the database server have been successfully completed. Therefore, no queries or other commands can be sent until the initialization phase is complete. The following is the code for such a sample module (the db.js file).

Get hands-on with 1200+ tech skills courses.