Last active
March 3, 2020 18:14
-
-
Save shannonmoeller/33d6173285a13862111690639ee7f819 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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