From the outside in, from the inside out. It’s like digging a tunnel through an onion, and we go through, first the outermost layer, then the innermost layer, then the outermost layer again. Let’s look at an example of code, four pieces of middleware, executed in sequence, and what is the final output?
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next) => {
ctx.body = 'Model Onion';
console.log("= =");
next();
console.log("= =");
})
app.use((ctx, next) => {
console.log("= = = =");
next();
console.log("= = = =");
})
app.use((ctx, next) => {
console.log("= = = = = =");
next();
console.log("= = = = = =");
})
app.use((ctx, next) => {
console.log("= = = = = = = =");
next();
console.log("= = = = = = = =");
})
app.listen(3000);
console.log('server is running! ');
Copy the code
The following output is displayed: