-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyPromise.ts
61 lines (60 loc) · 1.77 KB
/
myPromise.ts
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
class myPromise {
static PENDING = Symbol()
static FULFILL = Symbol()
static REJECT = Symbol()
status: Symbol
result: any //失败原因
value: any //成功结果
callbackFulfill: any[]
callbackReject: any[]
constructor (exectors) {
this.status = myPromise.PENDING
this.value = undefined
this.result = undefined
this.callbackFulfill = []
this.callbackReject = []
try {
exectors(this.resolve, this.reject)
}catch (e) {
this.reject(e)
}
}
resolve = (res) => {
if (this.status === myPromise.PENDING) {
this.status = myPromise.FULFILL
this.value = res
setTimeout(() => {
if (this.callbackFulfill.length > 0) {
this.callbackFulfill.forEach(fn => {
fn(res)
})
}
})
}
}
reject = (res) => {
if (this.status === myPromise.PENDING) {
this.status = myPromise.REJECT
this.result = res
}
setTimeout(() => {
if (this.callbackReject.length > 0) {
this.callbackReject.forEach(fn => {
fn(res)
})
}
})
}
then (onFulfill, onReject){
onFulfill = typeof onFulfill == 'function' ? onFulfill : value => value
onReject = typeof onReject == 'function' ? onReject : value => value
if (this.status === myPromise.FULFILL) {
onFulfill(this.value)
} else if (this.status === myPromise.REJECT) {
onReject(this.result)
} else {
this.callbackFulfill.push(onFulfill)
this.callbackReject.push(onReject)
}
}
}