koa2洋蔥模型理解

對于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é)束,就像針穿過洋蔥一樣,從最外層進去,然后從最外層出來一樣

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容