Skip to content

Instantly share code, notes, and snippets.

@kjin
Last active January 24, 2018 23:30
Show Gist options
  • Save kjin/8fc78a8672a996f0f59de5b7e1877617 to your computer and use it in GitHub Desktop.
Save kjin/8fc78a8672a996f0f59de5b7e1877617 to your computer and use it in GitHub Desktop.
// async_hooks-based continuation-local storage (simplified)
const asyncHooks = require('async_hooks')
const contexts = {}
let current = {}
asyncHooks.createHook({
init: uid => {
contexts[uid] = current
},
before: uid => {
if (contexts[uid]) {
current = contexts[uid]
}
},
destroy: uid => {
delete contexts[uid]
}
}).enable()
module.exports = {
bindInCurrentContext: fn => { // akin to bind
const boundContext = current
return (...args) => {
const oldContext = current
current = boundContext
const result = fn(...args)
current = oldContext
return result
}
},
bindInNewContext: fn => { // akin to runAndReturn (but lazy)
return (...args) => {
const oldContext = current
current = {}
const result = fn(...args)
current = oldContext
return result
}
},
set: (k, v) => {
current[k] = v
},
get: k => current[k]
}
const { bindInCurrentContext, bindInNewContext, set, get } = require('./cls-ah')
const wait = ms => ({ then: (fn) => setTimeout(fn, ms) })
bindInNewContext(async () => {
set('key', 2)
console.log('A', get('key'))
await wait(0)
console.log('B', get('key'))
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment