Implement a function middlewares(...fns) that composes multiple middleware functions into a single callable function.
Each middleware receives two arguments:
context: an object shared across all middlewaresnext: a function that calls the next middleware in the chainThe composed function:
context object.next().This behavior is similar to the middleware system in frameworks like Koa.
Example
async function fn1(ctx, next) { ctx.stack.push('fn1-start'); await next(); ctx.stack.push('fn1-end'); } async function fn2(ctx, next) { ctx.stack.push('fn2-start'); await new Promise((resolve) => setTimeout(resolve, 1000)); await next(); ctx.stack.push('fn2-end'); } function fn3(ctx, next) { ctx.stack.push('fn3-start'); next(); ctx.stack.push('fn3-end'); } const composedFn = middlewares(fn1, fn2, fn3); const context = { stack: [] }; await composedFn(context); console.log(context.stack); // ['fn1-start', 'fn2-start', 'fn3-start', 'fn3-end', 'fn2-end', 'fn1-end']
JavaScript Function
No test results yet
Click "Run" to execute tests