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.
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.
Koa is a middleware framework that can take two different kinds of functions as middleware: async function. common function.
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:
app.use
that you fired here was the middleware
. So the request flow goes into that one first, logs 1
to the console. await next()
, it downstreams to the next use
. 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. 3
to the console.Hope this makes it a little more clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With