koa2洋葱模型理解

2020-03-12  本文已影响0人  may505

对于koa洋葱模式,只有实践了才能知道什么是洋葱模式


image.png
const Koa = require("koa")
const app = new Koa()

// middleware one
app.use(async (ctx, next) => {
    console.log("中间件一开始");
    await next() // 调用下一个中间件
    console.log("中间件一结束");
})

// middleware two
app.use(async (ctx, next) => {
    const startTime = new Date().getTime()
    console.log("中间件二开始");
    await next() // 处理下一个中间件
    console.log("中间件二结束");
    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)

执行结果


image.png

从执行结果中可以看出,从第一个中间件开始,最后从第一个中间件结束,就像针穿过洋葱一样,从最外层进去,然后从最外层出来一样

上一篇下一篇

猜你喜欢

热点阅读