Last active
September 8, 2022 15:21
-
-
Save countcain/d8061f688c05a13561acf4b2cceda0ba to your computer and use it in GitHub Desktop.
Node 16 Async Storage
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 {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) | |
}) |
Author
countcain
commented
Sep 8, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment