-
Notifications
You must be signed in to change notification settings - Fork 27
/
实现promise.js
45 lines (45 loc) · 1.32 KB
/
实现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
class MyPro {
static PENDING = 'PENDING'
static FULFILLED = 'FULFILLED'
static REJECTED = 'REJECTED'
constructor(executor) {
this.status = MyPro.PENDING
this.value = null
this.reason = null
this.onFulfilledCb = []
this.onRejectedCb = []
try {
executor(this.resolve, this.reject)
} catch (e) {
this.reject(e)
}
}
resolve = (value) => {
if (this.status === MyPro.PENDING) {
this.status = MyPro.FULFILLED
this.value = value
this.onFulfilledCb.forEach(cb => cb(value))
}
}
reject = (reason) => {
if (this.status === MyPro.PENDING) {
this.status = MyPro.REJECTED
this.reason = reason
this.onFulfilledCb.forEach(cb => cb(reason))
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value
onRejected = typeof onRejected === "function" ? onRejected : reason => { throw reason }
if (this.status === MyPro.FULFILLED) {
setTimeout(() => onFulfilled(this.value))
} else if (this.status === MyPro.REJECTED) {
setTimeout(() => onRejected(this.reason))
} else if (this.status === MyPro.PENDING) {
this.onFulfilledCb.push(onFulfilled)
this.onRejectedCb.push(onRejected)
}
// 这里并没有实现真正的链式调用
return this
}
}