Skip to content

Instantly share code, notes, and snippets.

@Jabher
Created November 10, 2017 13:43
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 Jabher/45a003bea3cf6f6f252c72a3454c8954 to your computer and use it in GitHub Desktop.
Save Jabher/45a003bea3cf6f6f252c72a3454c8954 to your computer and use it in GitHub Desktop.
const async_hooks = require('async_hooks');
const triggerMap = {};
const asyncId = async_hooks.executionAsyncId();
const triggerId = async_hooks.triggerAsyncId();
const envs = {};
global.env = undefined;
let lastResolvedPromiseAsyncId;
const hooks = {
init(asyncId, type, triggerAsyncId) {
triggerMap[asyncId] = triggerAsyncId;
envs[asyncId] = Object.create(envs[triggerMap[asyncId]] || null );
},
before(asyncId) {
lastResolvedPromiseAsyncId = undefined;
global.env = envs[asyncId];
},
after(asyncId) {
envs[asyncId] = global.env;
Object.keys(triggerMap).forEach(triggeredAsyncId => {
if (triggerMap[triggeredAsyncId] === asyncId) {
Reflect.setPrototypeOf(envs[triggeredAsyncId], global.env);
}
});
global.env = envs[triggerMap[asyncId]];
},
promiseResolve(asyncId) {
lastResolvedPromiseAsyncId = asyncId;
}
};
hooks.init(asyncId, 'Root', triggerId);
hooks.before(asyncId);
async_hooks.createHook(hooks).enable();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment