-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
148 lines (89 loc) · 1.94 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/**
* Onion ring model
*/
async function fn1(next) {
console.log('fn1')
await next()
console.log('end fn1')
}
async function fn2(next) {
console.log('fn2')
await delay()
await next()
console.log('end fn2')
}
function fn3(next) {
console.log('fn3')
}
function delay() {
return new Promise((resolve, reject) => {
setTimeout(() =>{
resolve()
}, 2000)
})
}
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 next() {
return dispatch(i + 1)
}))
}
}
}
const middlewares = [fn1, fn2,fn3]
const finalFn = compose(middlewares)
finalFn()
// /**
// * 中间件
// */
// function add (x, y) {
// return x + y;
// }
// function double (z) {
// return z * 2
// }
// // const res1 = add(1, 2)
// // const res2 = double(res1)
// // console.log(res2)
// // const res3 = double(add(1, 2))
// // console.log(res3)
// const middlewares = [add, double]
// let len = middlewares.length
// function compose(midds) {
// return (...args) => {
// // 初始值
// console.log('...args', ...args)
// let res = midds[0](...args)
// console.log('res', res)
// for (let i = 1; i < len; i++) {
// res = midds[i](res)
// }
// return res
// }
// }
// const fn = compose(middlewares)
// const res = fn(1,2)
// console.log(res)
/**
* get
* set
*/
// let yuze = {
// _name: '语择',
// get name() {
// return this._name
// },
// set name(value) {
// console.log('new name is '+ value)
// this._name = value
// }
// }
// console.log(yuze.name)
// yuze.name = 'yoa'
// console.log(yuze.name)