Skip to content

Instantly share code, notes, and snippets.

@atian25
Created December 22, 2022 02:34
Show Gist options
  • Save atian25/c0240181dfa550449d76318a974c317c to your computer and use it in GitHub Desktop.
Save atian25/c0240181dfa550449d76318a974c317c to your computer and use it in GitHub Desktop.
AsyncLocalStorage
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