Skip to content

Instantly share code, notes, and snippets.

@shannonmoeller
Last active Mar 3, 2020
Embed
What would you like to do?
function createCascade() {
const middleware = [];
async function run(ctx, next = () => {}) {
// Reverse list to .pop() instead of .shift() for performance
const handlers = [...middleware, next].reverse();
async function runNext() {
if (handlers.length) {
const handler = handlers.pop();
await handler(ctx, runNext);
}
}
await runNext();
return ctx;
}
run.use = (handler) => {
middleware.push(handler);
return run;
};
return run;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment