In a nutshell, the cascading in Koa works by invoking middleware downstream sequentially and then controlling them to flow back upstream sequentially. It is best to create a simple Koa app to demonstrate this great feature in Koa:
- Create an index.js file in the /src/ directory, just like we did in the previous section:
// src/index.js
const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
console.log('Hello World')
ctx.body = 'Hello World'
})
app.listen(3000)
- Create three pieces of middleware just before the Hello World middleware as follows, so that we can run them first:
app.use(async (ctx, next) => {
console.log('Time started at: ', Date.now())
await next()
})
app.use(async (ctx, next) => {
console.log('I am the first')
await next()
console.log('I am the last')
})
app.use(async (ctx, next) => {
console.log('I am the second')
await...