Search code examples
koakoa-routerkoa2

Why do we await next when using koa routers?


Why do we do this

router.get('/data', async (ctx, next) => {
  ctx.body = dummyjson.parse(data);
  await next();
});

router.get('/data/:x', async (ctx, next) => {
  const newData = dataRepeat.replace('%(x)', ctx.params.x);
  ctx.body = dummyjson.parse(newData);
  await next();
});

What is the use of await next()

It would work just fine without that. Similar thing was expected with koa 1. yield next was added at the end of the router.


Solution

  • I'll try to explain it using a very simple example:

    const Koa = require('koa');
    const app = new Koa();
    
    // middleware
    app.use(async function (ctx, next) {
        console.log(1)
        await next();
        console.log(3)
    });
    
    // response
    app.use(ctx => {
        console.log(2)
    });
    
    app.listen(3000);
    

    If you call localhost:3000 in your browser, the following will happen in your app:

    • The first app.use that you fired here was the middleware. So the request flow goes into that one first, logs 1to the console.
    • Then, when you see this await next(), it downstreams to the next use.
    • Here we just log 2 to the console. When this is finished (and no further await next is seen in the second use) the flow goes back to the first one which actually waited till the second one was finished.
    • Here we then continue with logging 3 to the console.

    Hope this makes it a little more clear.