美文网首页
koa2洋葱模型理解

koa2洋葱模型理解

作者: may505 | 来源:发表于2020-03-12 10:20 被阅读0次

    对于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

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

    相关文章

      网友评论

          本文标题:koa2洋葱模型理解

          本文链接:https://www.haomeiwen.com/subject/wjlyjhtx.html