Skip to content

Instantly share code, notes, and snippets.

@FND
Created July 17, 2023 07:36
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 FND/552918beca7bdb901ffb07be539e2405 to your computer and use it in GitHub Desktop.
Save FND/552918beca7bdb901ffb07be539e2405 to your computer and use it in GitHub Desktop.
AsyncLocalStorage MTC
import { withCounter, withContext, log } from "./util.mjs";
let delay = 200;
log("TOKEN");
withContext("abc123", () => {
log("🅰️");
setTimeout(() => {
log("🅱️");
}, delay * 2);
});
log("COUNTER");
withCounter(() => {
log("1️⃣");
setTimeout(() => {
log("2️⃣");
}, delay);
});
log("EOF");
import { AsyncLocalStorage } from "node:async_hooks";
let store = new AsyncLocalStorage();
export function withCounter(fn) {
store.run({ count: 0 }, fn);
}
export function withContext(ctx, fn) {
store.run(ctx, fn);
}
export function log(msg) {
let ctx = store.getStore();
if (Number.isInteger(ctx?.count)) {
ctx.count++;
}
let prefix = msg.padEnd(10, " ")
console.log(prefix, ctx ?? "missing context store");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment