對于koa洋蔥模式,只有實踐了才能知道什么是洋蔥模式
image.png
const Koa = require("koa")
const app = new Koa()
// middleware one
app.use(async (ctx, next) => {
console.log("中間件一開始");
await next() // 調(diào)用下一個中間件
console.log("中間件一結(jié)束");
})
// middleware two
app.use(async (ctx, next) => {
const startTime = new Date().getTime()
console.log("中間件二開始");
await next() // 處理下一個中間件
console.log("中間件二結(jié)束");
const spendMs = new Date().getTime() - startTime
})
// middleware three
app.use(async (ctx, next) => {
console.log("++++");
await next()
ctx.response.type = "text/html"
ctx.response.body = "koa洋蔥模式"
console.log("----");
})
app.listen(3000)
執(zhí)行結(jié)果
image.png
從執(zhí)行結(jié)果中可以看出,從第一個中間件開始,最后從第一個中間件結(jié)束,就像針穿過洋蔥一樣,從最外層進去,然后從最外層出來一樣