Created
December 22, 2022 02:34
-
-
Save atian25/c0240181dfa550449d76318a974c317c to your computer and use it in GitHub Desktop.
AsyncLocalStorage
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
import { AsyncLocalStorage } from 'async_hooks'; | |
class App { | |
private asyncLocalStorage = new AsyncLocalStorage(); | |
private middlewares = []; | |
async use(fn, opts) { | |
const mw = fn(this, opts); | |
this.middlewares.push(mw); | |
} | |
getContext() { | |
return this.asyncLocalStorage.getStore(); | |
} | |
async run() { | |
try { | |
const ctx = { url: 'https://github.com' }; | |
await this.asyncLocalStorage.run(ctx, async () => { | |
for (const fn of this.middlewares) { | |
await fn(); | |
} | |
}); | |
} catch (err) { | |
console.error(err); | |
} | |
} | |
} | |
function m1(app, opts) { | |
return async () => { | |
const ctx = app.getContext(); | |
Object.assign(ctx, opts); | |
console.log('m1', ctx); | |
}; | |
} | |
const app = new App(); | |
app.use(m1, { a: 1 }); | |
app.use(m1, { b: 1 }); | |
app.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment