域和 promise
¥Domains and promises
从 Node.js 8.0.0 开始,promise 的句柄在调用 .then()
或 .catch()
本身的域内运行:
¥As of Node.js 8.0.0, the handlers of promises are run inside the domain in
which the call to .then()
or .catch()
itself was made:
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then((v) => {
// running in d2
});
});
可以使用 domain.bind(callback)
将回调绑定到特定域:
¥A callback may be bound to a specific domain using domain.bind(callback)
:
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then(p.domain.bind((v) => {
// running in d1
}));
});
域不会干扰 promise 的错误处理机制。换句话说,对于未处理的 Promise
拒绝,不会触发 'error'
事件。
¥Domains will not interfere with the error handling mechanisms for
promises. In other words, no 'error'
event will be emitted for unhandled
Promise
rejections.