Skip to content

Instantly share code, notes, and snippets.

@Conduitry
Last active June 24, 2017 07:58
Show Gist options
  • Save Conduitry/8042c0c7af1f9968aa4d76f0687dbade to your computer and use it in GitHub Desktop.
Save Conduitry/8042c0c7af1f9968aa4d76f0687dbade to your computer and use it in GitHub Desktop.
Async Local Context
// Async Local Context
// Requires Node.js nightly features and fixes, planned (I believe) to be released in 8.2.0
// Call `createContext()` to create a new local context.
// Call `getContext()` anywhere under that to retrieve the same local context.
// Call `createContext()` when there is already an existing context to create a new child context which inherits from the parent.
import { createHook, executionAsyncId } from 'async_hooks'
let contexts = new Map()
createHook({
init(asyncId, type, triggerAsyncId) {
contexts.set(asyncId, contexts.get(triggerAsyncId))
},
destroy(asyncId) {
contexts.delete(asyncId)
},
}).enable()
export function createContext() {
contexts.set(executionAsyncId(), Object.create(getContext() || null))
}
export function getContext() {
return contexts.get(executionAsyncId())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment