-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathstep1.js
More file actions
72 lines (69 loc) · 2.19 KB
/
step1.js
File metadata and controls
72 lines (69 loc) · 2.19 KB
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
class myPromise {
static PENDING = 'pending';
static FULFILLED = 'fulfilled';
static REJECTED = 'rejected';
constructor(func) {
this.PromiseState = myPromise.PENDING;
this.PromiseResult = null;
this.onFulfilledCallbacks = []; // 保存成功回调
this.onRejectedCallbacks = []; // 保存失败回调
try {
func(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error)
}
}
resolve(result) {
if (this.PromiseState === myPromise.PENDING) {
setTimeout(() => {
this.PromiseState = myPromise.FULFILLED;
this.PromiseResult = result;
this.onFulfilledCallbacks.forEach(callback => {
callback(result)
})
});
}
}
reject(reason) {
if (this.PromiseState === myPromise.PENDING) {
setTimeout(() => {
this.PromiseState = myPromise.REJECTED;
this.PromiseResult = reason;
this.onRejectedCallbacks.forEach(callback => {
callback(reason)
})
});
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => {
throw reason;
};
if (this.PromiseState === myPromise.PENDING) {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
}
if (this.PromiseState === myPromise.FULFILLED) {
setTimeout(() => {
onFulfilled(this.PromiseResult);
});
}
if (this.PromiseState === myPromise.REJECTED) {
setTimeout(() => {
onRejected(this.PromiseResult);
});
}
}
}
// 测试代码
let p1 = new myPromise((resolve, reject) => {
resolve(10)
})
p1.then(res => {
console.log('fulfilled', res);
return 2 * res
}).then(res => {
console.log('fulfilled', res)
})
// [referer](https://juejin.cn/post/7043758954496655397)