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:

    Hope this makes it a little more clear.