哈喽,大家好呀,我是前端理想哥,今天我们来聊聊Koa的洋葱模型。
洋葱模型其实是一种使用中间件处理流程的设计模式,可以通过把请求和响应对象传递给一系列中间件函数进行处理,最终返回响应结果。
接下来,我们先来看看下面这道题目:
const Koa = require("koa")
const app = new Koa();
// 中间件1
app.use(async (ctx, next) => {
console.log("1")
await next()
console.log("2")
});
// 中间件2
app.use(async (ctx, next) => {
console.log("3")
await next()
console.log("4")
});
// 中间件3
app.use(async (ctx, next) => {
console.log("5")
await next()
console.log("6")
});
app.listen(8001);
这道题中,我们定义了三个中间件,并在每个中间件中都执行了next方法,并在next方法前后都打印出了数字,最终输出的答案是:1 3 5 6 4 2
可能有的同学会很疑惑,为什么1执行完了,直接输出3,而不是2呢?为了说明这个问题,我们得来看看这张图: