洋葱圈模型

学习Egg的时候,对洋葱圈模型很疑惑,不知道它有啥好处,听了组长的讲解,确实大有好处,记录记录

看例子

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// app.js

const Koa = require('koa2');
const app = new Koa();

// logger
app.use(async (ctx, next) => {
console.log('第一层洋葱 - 开始')
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
console.log('第一层洋葱 - 结束')
});

// x-response-time
app.use(async (ctx, next) => {
console.log('第二层洋葱 - 开始')
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
console.log('第二层洋葱 - 结束')
});

// response
app.use(async ctx => {
console.log('第三层洋葱 - 开始')
ctx.body = 'Hello World';
console.log('第三层洋葱 - 结束')
});

app.listen(8000);

img

分析

首先看到它相比于express的责任链模型,多了async await这样方便的语法,摒弃了express的callback写法,使代码看起来更加优雅简洁。

然后因为有了await,对stream支持度更高,对错误处理更加友好。比如请求1-2-3,返回3-2-1,便可以在返回的途中进行数据处理,而express是不行的。