forked from FE-star/homework8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (43 loc) · 1.21 KB
/
index.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
function myPromise(constructor) {
let self = this;
self.status = "pending"; //定义状态改变前的初始状态
self.value = undefined; //定义状态为resolved的时候的状态
self.reason = undefined; //定义状态为rejected的时候的状态
self.fulfillTasks = [];
self.rejectTasks = [];
function resolve(value) {
if (self.status !== "pending") return;
self.status = "fulfilled";
self.value = value;
self.fulfillTasks.forEach((fn) => fn());
}
function reject(reason) {
if (self.status !== "pending") return;
self.status = "rejected";
self.reason = reason;
self.rejectTasks.forEach((fn) => fn());
}
//捕获构造异常
try {
constructor(resolve, reject);
} catch (e) {
reject(e);
}
}
myPromise.prototype.then = function (onFullfilled, onRejected) {
// skip creating new promise
if (this.status === "fulfilled") {
onFullfilled(this.value);
} else if (this.status === "rejected") {
onRejected(this.reason);
}
if (this.status === "pending") {
this.fulfillTasks.push(() => {
onFullfilled(this.value);
});
this.rejectTasks.push(() => {
onRejected(this.reason);
});
}
};
module.exports = myPromise;