-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (57 loc) · 1.28 KB
/
index.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
module.exports = seq
function seq(initialFns) {
const flow = {}
const fns = initialFns
? Array.isArray(initialFns)
? [...initialFns]
: [initialFns]
: []
flow.add = add
flow.run = run
return flow
function add(fn) {
if (typeof fn !== 'function') {
throw new Error('Expected `fn` to be a function, not ' + fn)
}
fns.push(fn)
// 方便链式调用
return flow
}
function run(initialArg) {
let index = -1
let input = initialArg
let finish
let error
return new Promise((resolve, reject) => {
finish = () => resolve(input)
error = err => reject(err)
next()
})
function next(arg) {
// 如果有新的参数,设置新的参数
input = arg || input
if (index === fns.length - 1) {
finish()
return
}
const fn = fns[++index]
if (typeof fn !== 'function') {
throw new Error('fn must be a function' + (index - 1))
}
const result = wrap(fn)(input)
result.then(next, error)
}
}
}
function wrap(fn) {
return function wrapped(...args) {
return new Promise((resolve, reject) => {
try {
const result = fn(...args)
resolve(result)
} catch (err) {
reject(err)
}
})
}
}