Requiring asynchronously initialized modules
In Chapter 1, Node.js Design Fundamentals, when we discussed the fundamental properties of the Node.js module system, we mentioned the fact that require()
works synchronously and that module.exports
cannot be set asynchronously.
This is one of the main reasons for the existence of synchronous API in the core modules and many npm
packages, they are provided more as a convenient alternative, to be used primarily for initialization tasks rather than a substitute for asynchronous API.
Unfortunately, this is not always possible; a synchronous API might not always be available, especially for components using the network during their initialization phase, for example, to perform handshake protocols or to retrieve configuration parameters. This is the case for many database drivers and clients for middleware systems such as message queues.
Canonical solutions
Let's take an example: a module called db
, which connects to a remote database. The db
module will...