4

I'm trying to wrap my head around the way koajs cascades by awaiting on "next()" before resuming request processing. As far as I can tell, "next" simply refers to the next sequential app.use() in the script.

Can someone more familiar with koajs confirm this? For example, would this code (modified from koajs.com) still work (foo and bar used to be "next")?

app.use(async (ctx, foo) => {
  const start = Date.now();
  await foo();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

app.use(async (ctx, bar) => {
  const start = Date.now();
  await bar();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

app.use(async ctx => {
  ctx.body = 'Hello World';
});

Or is there something magical about using "next" (besides good semantics)? I'm assuming not, and the behavior is just dependent on the argument order in the function.

If this is the case, then how is it possible to control the flow from one app.use() to another? For example something like this pseudo code:

   app.use(async (ctx, a, b) => {
    if (!ctx.something) {
    await a();
    } else {
    await b();
    }
   }

   let a = app.use(.....);
   let b = app.use(.....);

Any help is appreciated, and also, feel free to point me to an appropriate resource if I've missed something simple.

MFave
  • 1,044
  • 2
  • 8
  • 19

2 Answers2

0

There is nothing magical about calling the second parameter to your middleware next. You are free to call it foo or bar or any other legal name (though of course future programmers will find it confusing!).

Middleware in Koa works in a single stack-like manner, so its not possible to provide multiple middlewares as possible "next" actions as in your second example.

You can implement conditional execution by wrapping middlewares inside of each other though. There is a good example in the Koa github repo.

mradamh
  • 86
  • 6
0

As soon as the next is called, the control moves to next middleware and the next middleware is stacked up in the execution, this means when the immediate next middleware finishes up its execution, it will be removed from the stack and the control will return again to the middleware where next was called. Since this means every line of the middleware would be executed anyways, no matter when you call next, you cannot see the difference in output. Think of something as what would happen if you call a function inside another function.

Anurag Shukla
  • 186
  • 3
  • 11