Skip to content

Instantly share code, notes, and snippets.

@winguse
Created August 7, 2018 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winguse/07cf4719399fae42b7bf0af91fcc2e84 to your computer and use it in GitHub Desktop.
Save winguse/07cf4719399fae42b7bf0af91fcc2e84 to your computer and use it in GitHub Desktop.
const asyncHooks = require('async_hooks');
const contextStore = new Map();
class Context {
constructor() {
this.id = Math.random();
}
}
const asyncHook = asyncHooks.createHook({
init(asyncId, type, triggerAsyncId, resource) {
const parentContext = contextStore.get(triggerAsyncId);
if (parentContext) {
contextStore.set(asyncId, parentContext);
}
},
destroy(asyncId) {
contextStore.delete(asyncId);
}
});
asyncHook.enable();
function setContext() {
contextStore.set(asyncHooks.executionAsyncId(), new Context());
}
function getContext() {
return contextStore.get(asyncHooks.executionAsyncId());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment