Created
May 11, 2023 23:05
-
-
Save qpwo/7d067ad6456b629939b9a778d6549331 to your computer and use it in GitHub Desktop.
node js async context trace
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
import { AsyncLocalStorage } from 'node:async_hooks' | |
const asyncLocalStorage = new AsyncLocalStorage<number>() | |
async function sleep(ms: number) { | |
return new Promise(resolve => setTimeout(resolve, ms)) | |
} | |
async function foo() { | |
console.log('started') | |
await sleep(1000) | |
console.log(asyncLocalStorage.getStore()) | |
} | |
for (let i = 0; i < 10; i++) { | |
asyncLocalStorage.run(i, foo) | |
} | |
// output: started started started ... 0 1 2 3 4 5 6 7 8 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment