Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 996
relidon Avatar asked Mar 01 '17 13:03

relidon


People also ask

What is Koa next?

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling.

What is middleware KOA?

Koa is a middleware framework that can take two different kinds of functions as middleware: async function. common function.


1 Answers

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.

like image 105
Sebastian Hildebrandt Avatar answered Oct 02 '22 16:10

Sebastian Hildebrandt