-
Notifications
You must be signed in to change notification settings - Fork 181
/
11.promise.js
123 lines (105 loc) · 2.41 KB
/
11.promise.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
class MyPromise {
constructor (exe) {
this.value = undefined
this.status = 'pending'
this.successQueue = []
this.failureQueue = []
const resolve = () => {
const doResolve = (value) => {
if (this.status === 'pending') {
this.status = 'success'
this.value = value
while (this.successQueue.length) {
const cb = this.successQueue.shift()
cb && cb(this.value)
}
}
}
setTimeout(doResolve, 0)
}
const reject = () => {
const doReject = (value) => {
if (this.status === 'pending') {
this.status = 'failure'
this.value = value
while (this.failureQueue.length) {
const cb = this.failureQueue.shift()
cb && cb(this.value)
}
}
}
setTimeout(doReject, 0)
}
exe(resolve, reject)
}
then (success = (value) => value, failure = (value) => value) {
return new MyPromise((resolve, reject) => {
const successFn = (value) => {
try {
const result = success(value)
result instanceof MyPromise ? result.then(resolve, reject) : resolve(result)
} catch (err) {
reject(err)
}
}
const failureFn = (value) => {
try {
const result = failure(value)
result instanceof MyPromise ? result.then(resolve, reject) : resolve(result)
} catch (err) {
reject(err)
}
}
if (this.status === 'pending') {
this.successQueue.push(successFn)
this.failureQueue.push(failureFn)
} else if (this.status === 'success') {
success(this.value)
} else {
failure(this.value)
}
})
}
catch () {
}
}
const pro = new MyPromise((resolve, reject) => {
setTimeout(resolve, 1000)
setTimeout(reject, 2000)
})
pro
.then(() => {
console.log('2_1')
const newPro = new MyPromise((resolve, reject) => {
console.log('2_2')
setTimeout(reject, 2000)
})
console.log('2_3')
return newPro
})
.then(
() => {
console.log('2_4')
},
() => {
console.log('2_5')
}
)
pro
.then(
data => {
console.log('3_1')
throw new Error()
},
data => {
console.log('3_2')
}
)
.then(
() => {
console.log('3_3')
},
e => {
console.log('3_4')
}
)