Is it possible to exit a domain asynchronously with respect to when it was entered? My "stack" mental model of domains is apparently insufficient because I expected this to succeed:
var Domain = require('domain');
var assert = require('assert');
var outerDomain = Domain.create();
outerDomain.name = 'outer';
outerDomain.run(function() {
var innerDomain = Domain.create();
innerDomain.name = 'inner';
innerDomain.enter();
setImmediate(function() {
assert.strictEqual(process.domain.name, 'inner');
process.domain.exit();
// This assertion is failing because process.domain is undefined!
assert.strictEqual(process.domain.name, 'outer');
});
});
The second assertion is failing because there is no active domain, whereas I expect the "outer" domain to be active.
I'd appreciate an understanding of why this fails.
Ok I think I shored up my mental model of how domains work:
When I call
setImmediate, the anonymous function is only bound to the active domain, without any knowledge of the entire domain "stack".So once you cross an async gap, the domain "stack" is lost, and only the active domain remains.