Skip to content

Instantly share code, notes, and snippets.

@wreulicke
Created February 6, 2021 01:37
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 wreulicke/6a0027cd78dc92e56846c7eeaa0c58c4 to your computer and use it in GitHub Desktop.
Save wreulicke/6a0027cd78dc92e56846c7eeaa0c58c4 to your computer and use it in GitHub Desktop.
async_hooksで遊んでみた
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