Created
November 5, 2021 15:49
-
-
Save KelWill/1f9e8d63cc012312cab4fbced8936ef6 to your computer and use it in GitHub Desktop.
This file contains 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
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