模拟koa洋葱模型实现

koa洋葱模型即是注册的中间件采取先进后出的运行策略。

问题

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
app.use(async next => {
console.log(1);
await next();
console.log(2);
});
app.use(async next => {
console.log(3);
await next();
console.log(4);
});

// 异步函数
function fn() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("hello");
}, 3000);
});
}
app.use(async next => {
console.log(5);
let res = await fn(); // 调用异步函数
console.log(res)
await next();
console.log(6);
});

app.compose();

实现use与compose方法,预期输出如下结果

1
2
3
4
5
6
7
1
3
5
hello
6
4
2

方法实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var app = {
middlewares: []
};

// 创建 use 方法
app.use = function(fn) {
app.middlewares.push(fn);
};

app.compose = function() {
// 递归函数
function dispatch(index) {
// 如果所有中间件都执行完跳出
if (index === app.middlewares.length) return Promise.resolve();

// 取出第 index 个中间件并执行
const middleware = app.middlewares[index];
// 核心在这一行
return Promise.resolve(middleware(() => dispatch(index + 1)));
}

// 取出第一个中间件函数执行
dispatch(0);
};

留言

欢迎交流想法。留言会通过 GitHub Issues 保存,首次使用需要登录 GitHub。