洋葱模型

egg和koa的洋葱模型 指的是中间件流程控制机制。

如下图,所有的请求经过一个中间件的时候都会执行两次,对比 Express 形式的中间件,Koa 的模型可以非常方便的实现后置处理逻辑,对比 Koa 和 Express 的 Compress 中间件就可以明显的感受到 Koa 中间件模型的优势。

洋葱模型_第1张图片

代码例子(koa):

// #1
app.use(async (ctx, next)=>{

    console.log(1)

    await next(); 

   console.log(1)

});

// #2
    app.use(async (ctx, next) => {

    console.log(2)

    await next();

    console.log(2)

}) 

app.use(async (ctx, next) => {

    console.log(3)

}) 

上面代码的输出顺序是:

1
2
3
2
1

你可能感兴趣的:(洋葱模型)