import EventEmitter from 'events'; | |
import { | |
AsyncResource, | |
executionAsyncId, | |
createHook, | |
} from 'async_hooks'; | |
const zones = new Map(); | |
export default class Zone extends EventEmitter { | |
#name; | |
#resource; | |
static get current() { | |
return zones.get(executionAsyncId()); | |
} | |
constructor({ name = null } = {}) { | |
super(); | |
this.#name = name; | |
this.#resource = new AsyncResource('ZONE', { | |
triggerAsyncId: executionAsyncId(), | |
requireManualDestroy: false, | |
}); | |
zones.set(this.#resource.asyncId(), this); | |
} | |
run(fn, ...args) { | |
let r; | |
try { | |
r = this.#resource.runInAsyncScope(fn, undefined, ...args); | |
if (typeof r.then === 'function') { | |
r.then(undefined, (err) => { | |
this.emit('error', err); | |
}); | |
} | |
} catch (err) { | |
this.emit('error', err); | |
} | |
return r; | |
} | |
fork({ name } = {}) { | |
const z = new Zone({ name }); | |
return z; | |
} | |
get name() { | |
return this.#name; | |
} | |
get parent() { | |
return zones.get(this.#resource.triggerAsyncId()); | |
} | |
} | |
zones.set(executionAsyncId(), new Zone()); | |
createHook({ | |
init: (asyncId, type, triggerAsyncId) => { | |
zones.set(asyncId, zones.get(triggerAsyncId)); | |
}, | |
destroy: (asyncId) => { | |
zones.delete(asyncId); | |
}, | |
}).enable(); | |
process.on('multipleResolves', (type, promise, value) => { | |
Zone.current.emit('multipleResolves', type, promise, value); | |
}); | |
process.on('unhandledRejection', (reason, promise) => { | |
Zone.current.emit('unhandledRejection', reason, promise); | |
}); | |
process.on('rejectionHandled', (promise) => { | |
Zone.current.emit('rejectionHandled', promise); | |
}); |
This comment has been minimized.
This comment has been minimized.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Currently child zones don't work with
unhandledRejection
/rejectionHandled
e.g. this never prints anything:This happens because
process.on('unhandledRejection' | 'rejectionHandled'
is always run inexecutionAsyncId() === 0
which meansZone.current
is never themainZone
in those callbacks.I'm not sure how to repair it either, all that is received inside
process.on('unhandledRejection'
is thepromise
(and its reason) which can't be used to extract theasyncId
of thePromiseWrap
as far as I can tell.