-
Notifications
You must be signed in to change notification settings - Fork 1
/
compose_test.js
49 lines (43 loc) · 896 Bytes
/
compose_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
45
46
47
48
49
async function fn1(next) {
console.log('fn1')
next && await next()
console.log('fn1 end')
}
async function fn2(next) {
console.log('fn2')
next && await next()
console.log('fn2 end')
}
async function fn3(next) {
console.log('fn3')
next && await next()
console.log('fn3 end')
}
// fn3(fn2(fn1()))
// const compose = (middlewares) => () => {
// [first, ...others] = middlewares
// let ret = first()
// others.forEach(fn => {
// ret = fn(ret)
// })
// return ret
// }
function compose(middlewares) {
return function () {
return dispatch(0)
function dispatch(i) {
let fn = middlewares[i]
if (!fn) {
return Promise.resolve()
}
return Promise.resolve(
fn(function () {
return dispatch(i + 1)
})
)
}
}
}
const middlewares = [fn1, fn2, fn3]
const finalFn = compose(middlewares)
finalFn()