Created
June 20, 2019 03:28
-
-
Save devsnek/07a61aec7d9f40d1495048790dd30a8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.