-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
44 lines (40 loc) · 998 Bytes
/
test.js
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
33
34
35
36
37
38
39
40
41
42
43
44
const App = function () {
let context = {}
let middlewares = []
return {
// 将中间件放入队列中
use (fn) {
middlewares.push(fn)
},
// 调用中间件
callback () {
// compose(middleware)
// 初始调用第 1 个中间件
return dispatch(0)
function dispatch(i) {
let fn = middlewares[i]
// 执行中间件,回调参数是:公共数据、调用下一个中间件函数
// 返回一个 Promise 实例
return Promise.resolve(
fn(context, function next () { dispatch(i + 1) })
)
}
},
}
}
let app = App()
app.use(async (cxt, next) => {
console.log('middleware_01 start')
await next()
console.log('middleware_01 end')
})
app.use(async (cxt, next) => {
console.log('middleware_02 start')
await next()
console.log('middleware_02 end')
})
app.use(async (cxt, next) => {
console.log('middleware_03 start')
console.log('middleware_03 end')
})
app.callback()