0%

简易 Koa 洋葱模型

手写 Koa 洋葱模型

效果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const app = new Koa()
app.use(async (next) => {
console.log(1)
await next()
console.log(2)
})
app.use(async (next) => {
console.log(3)
await next()
console.log(4)
})
app.compose()
// 打印1,3,2,4

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
function compose(...funcs) {
return function (v) {
return funcs.reduce((p, cb) => {
return p.then(() => cb)
}, v)
}
}

class Koa {
constructor() {
this.middleware = []
}
compose() {
const resolve = () => {}
const reject = () => {}
const dispatch = (i) => {
const fn = this.middleware[i]
if (!fn) return Promise.resolve()
return Promise.resolve(
fn(() => {
return dispatch(i + 1)
})
)
}
return dispatch(0)
}
use(cb) {
this.middleware.push(cb)
}
}