Created
February 6, 2021 01:37
-
-
Save wreulicke/6a0027cd78dc92e56846c7eeaa0c58c4 to your computer and use it in GitHub Desktop.
async_hooksで遊んでみた
This file contains hidden or 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
const async_hooks = require('async_hooks') | |
const map = new Map() | |
let beforeCount = 0 | |
let afterCount = 0 | |
const hook = async_hooks.createHook({ | |
init(asyncId, type, triggerAsyncId, resource) { | |
const context = map.get(triggerAsyncId) | |
if (!context) { | |
return | |
} | |
map.set(asyncId, { ...context }) | |
}, | |
before(asyncId) { | |
if (beforeCount % 500 === 0) { | |
console.log('before', asyncId) | |
} | |
beforeCount++ | |
}, | |
after(asyncId) { | |
if (afterCount % 500 === 0) { | |
console.log('after', asyncId) | |
} | |
afterCount++ | |
}, | |
promiseResolve(asyncId) {}, | |
destroy(asyncId) { | |
map.delete(asyncId) | |
}, | |
}) | |
hook.enable() | |
function getContext() { | |
const asyncId = async_hooks.executionAsyncId() | |
console.log('getContext', asyncId) | |
return map.get(asyncId) | |
} | |
function setContext(context) { | |
const asyncId = async_hooks.executionAsyncId() | |
map.set(asyncId, context) | |
} | |
function dumpContext() { | |
console.log(getContext()) | |
} | |
dumpContext() | |
setContext({ id: 'test' }) | |
dumpContext() | |
dumpContext() | |
dumpContext() | |
setTimeout(() => { | |
const asyncId = async_hooks.executionAsyncId() | |
console.log(asyncId) | |
dumpContext() | |
new Promise((r) => { | |
r() | |
}).then(() => { | |
const asyncId = async_hooks.executionAsyncId() | |
console.log(asyncId) | |
dumpContext() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment