Skip to content

Instantly share code, notes, and snippets.

@qpwo
Created May 11, 2023 23:05
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 qpwo/7d067ad6456b629939b9a778d6549331 to your computer and use it in GitHub Desktop.
Save qpwo/7d067ad6456b629939b9a778d6549331 to your computer and use it in GitHub Desktop.
node js async context trace
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