FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Middlewares

20mins

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 middlewares
  • next: a function that calls the next middleware in the chain

The composed function:

  • Accepts a context object.
  • Returns a Promise.
  • Executes middlewares sequentially and asynchronously.
  • Stops execution if a middleware does not call 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']

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests