A warning
First of all, the domains are outdated and will be removed in the upcoming version of NodeJS. I would not write new code using them.
How do domains work?
Secondly, itβs important to understand that domains are not magical. This is a really simple concept. They are mainly:
- Wrap each asynchronous call in the platform (all NodeJS APIs).
- Set the "global" variable for the duration of the call.
- If another asynchronous call is made during this call, save the note to set the global variable to the same value as you enter it.
- What is it.
Here, how domains can be implemented, let them only implement it for setTimeout for simplicity.
const oldTimeout = setTimeout; setTimeout = function(fn, ms) {
Something like express can simply do domain = new RequestContext at the beginning, and then all the methods called in the request will work, since they are all wrapped, as in the example above (since it is again baked in node).
It sounds waved, why remove them?
They are deleted because of the complexity of the implementation that they add, and the fact that they leak, and error recovery has extreme cases when they do not work.
So what should I do?
You have alternatives, for example bluebird promises have .bind , which bring the promise chain context, which is a less-missed way to do this.
However, I would simply avoid the implicit global context. It makes refactoring tough, it makes dependencies implicit, and it makes the code harder to reason about. I just passed the appropriate context to the objects when I create them (nesting in dependencies, in a nutshell), and not setting a global variable.
source share