Skip to content

Instantly share code, notes, and snippets.

@KelWill
Created November 5, 2021 15:49
Show Gist options
  • Save KelWill/1f9e8d63cc012312cab4fbced8936ef6 to your computer and use it in GitHub Desktop.
Save KelWill/1f9e8d63cc012312cab4fbced8936ef6 to your computer and use it in GitHub Desktop.
const { AsyncLocalStorage } = require("async_hooks");
const storageContext = new AsyncLocalStorage();
const middlewares = [];
function addMiddleware(callback) {
middlewares.push(callback);
}
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
addMiddleware((next) => storageContext.run("hello world!", next));
addMiddleware((next) => {
setTimeout(() => {
console.log("set timeout middleware", storageContext.getStore());
next();
}, 10);
});
addMiddleware(async (next) => {
await delay(100);
console.log("after delay middleware", storageContext.getStore());
});
addMiddleware((next) => next());
function runMiddleware() {
function runNext(i) {
const cb = middlewares[i];
cb(() => {
if (i < middlewares.length - 1) runNext(i + 1);
});
}
runNext(0);
}
runMiddleware();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment