Skip to content

Instantly share code, notes, and snippets.

@countcain
Last active September 8, 2022 15:21
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 countcain/d8061f688c05a13561acf4b2cceda0ba to your computer and use it in GitHub Desktop.
Save countcain/d8061f688c05a13561acf4b2cceda0ba to your computer and use it in GitHub Desktop.
Node 16 Async Storage
const {AsyncLocalStorage} = require('async_hooks')
const localStorage = new AsyncLocalStorage()
const sleep = () => new Promise(r=>setTimeout(r, 10))
const nestedFuncA = async () => {
await sleep()
const store = localStorage.getStore()
if (store) {
store['nested_a'] = 'nested_a'
}
await nestedFuncB()
}
const nestedFuncB = async () => {
await sleep()
const store = localStorage.getStore()
if (store) {
store['nested_b'] = 'nested_b'
}
}
const funcA = async () => {
await sleep()
const store = localStorage.getStore()
if (store) {
store['a'] = 'a'
}
await funcB()
}
const funcB = async () => {
await sleep()
const store = localStorage.getStore()
if (store) {
store['b'] = 'b'
}
await funcC()
}
const funcC = async () => {
await sleep()
const store = localStorage.getStore()
if (store) {
store['c'] = 'c'
}
localStorage.run(store, async () => {
await nestedFuncA()
const store = localStorage.getStore()
console.log('access store in nested function',store)
})
if (store) {
store['c_after_nested_call'] = 'c_after_nested_call'
}
}
localStorage.run({}, async () => {
await funcA()
const store = localStorage.getStore()
console.log('access store in main function', store)
})
@countcain
Copy link
Author

Screen Shot 2022-09-08 at 11 19 02 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment