手写Promise

Promise 基础版

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
class MyPromise {
static PENDING = "pending"
static FULFILLED = "fulfilled"
static REJECTED = "rejected"

constructor(fn) {
this.PromiseState = MyPromise.PENDING
this.PromiseResult = null
this.onFulfilledCallback = [] // 保存成功回调
this.onRejectedCallback = [] // 保存失败回调

try {
// 使this指向MyPromise
fn(this.resolve.bind(this), this.reject.bind(this))
} catch (error) {
this.reject(error)
}
}

resolve(result) {
this.PromiseState = MyPromise.FULFILLED
this.PromiseResult = result
this.onFulfilledCallback.forEach(callback => {
callback(this.PromiseResult)
})
}

reject(reason) {
this.PromiseState = MyPromise.REJECTED
this.PromiseResult = reason
this.onRejectedCallback.forEach(callback => {
callback(this.PromiseResult)
})
}

then(onFulfilled, onRejected) {
if (this.PromiseState === MyPromise.PENDING) {
this.onFulfilledCallback.push(() => {
setTimeout(() => {
onFulfilled(this.PromiseResult)
})
})
this.onRejectedCallback.push(() => {
setTimeout(() => {
onRejected(this.PromiseResult)
})
})
}

if (this.PromiseState === MyPromise.FULFILLED) {
setTimeout(() => {
onFulfilled(this.PromiseResult)
})
}

if (this.PromiseState === MyPromise.REJECTED) {
setTimeout(() => {
onRejected(this.PromiseResult)
})
}
}

catch(onRejected) {
if (this.PromiseState === MyPromise.PENDING) {
this.onRejectedCallback.push(() => {
setTimeout(() => {
onRejected(this.PromiseResult)
})
})
}

if (this.PromiseState === MyPromise.REJECTED) {
setTimeout(() => {
onRejected(this.PromiseResult)
})
}
}
}

实现 then 链式回调