Last active
June 24, 2017 07:58
-
-
Save Conduitry/8042c0c7af1f9968aa4d76f0687dbade to your computer and use it in GitHub Desktop.
Async Local Context
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
// 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