-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathPromise.js
103 lines (98 loc) · 2.71 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
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
class Promise {
constructor(executor) {
this.status = 'pending' // 默认状态
this.value // resolve 成功时的值
this.error // reject 失败时的值
this.resolveQueue = []; // 成功存放的数组
this.rejectQueue = []; // 失败存放法数组
// 定义 resolve
let resolve = (res) => {
if (this.status === 'pending') {
this.value = res
this.status = 'resolved'
// 一旦resolve执行,调用成功数组的函数
this.resolveQueue.forEach(fn => fn());
}
}
// 定义 reject
let reject = (err) => {
if (this.status === 'pending') {
this.error = err
this.status = 'rejected'
}
}
// 自动执行
executor(resolve, reject)
}
// 声明 then
then(onFullfilled, onRejected) {
let promise2;
if (this.status === 'resolved') {
onFullfilled(this.value)
}
if (this.status === 'rejected') {
onRejected(this.error)
}
// 当状态state为pending时
if (this.status === "pending") {
promise2 = new Promise((resolve, reject) => {
this.resolveQueue.push(() => {
let x = onFullfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
})
this.rejectQueue.push(() => {
let x = onRejected(this.error);
resolvePromise(promise2, x, resolve, reject);
})
})
}
return promise2;
},
catch (onRejected) {
return this.then(null, onRejected)
}
}
class Promise {
constructor(executor) {
this.status = "pending"
this.value
this.error
this.resolveQuene = []
this.rejectQuene = []
let resolve = (res) => {
if (this.status === 'pending') {
this.value = res
this.status = 'resolved'
this.resolveQuene.forEach(fn => fn())
}
}
let reject = (err) => {
if (this.status === 'pending') {
this.value = res
this.status = 'rejected'
}
}
executor(resolve, reject)
}
then(onFullfilled, onRejected) {
let promise2;
if (this.status == 'resolved') {
onFullfilled(this.value)
}
if (this.status == 'rejected') {
onRejected(this.error)
}
if (this.status == 'pending') {
promise2 = new Promise((resolve, reject) => {
this.resolveQuene.push(() => {
let x = onFullfilled(this.value)
resolvePromise(promise2, x, resolve, reject);
})
this.rejectQueue.push(() => {
let x = onRejected(this.error);
resolvePromise(promise2, x, resolve, reject);
})
})
}
}
}