Last active
January 24, 2018 23:30
-
-
Save kjin/8fc78a8672a996f0f59de5b7e1877617 to your computer and use it in GitHub Desktop.
This file contains 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
// 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] | |
} |
This file contains 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 { 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