-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.v2.js
53 lines (52 loc) · 1.53 KB
/
promise.v2.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
// 改进promise调用then的时,pending状态的处理
// 采用发布订阅模式: 如果当前状态是pending时, 需要将成功的回调和失败的回调存放起来,稍后调用resolve和reject时重新执行
const RESOLVED = "RESOLVED"; // 成功
const REJECTED = "REJECTED"; // 失败
const PENDING = "PENDING"; // 等待态
class Promise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = []; // 专门用来存放成功的回调
this.onRejectedCallbacks = []; // 专门用来存放失败的回调
let resolve = (value) => {
if (this.status === PENDING) {
this.value = value;
this.status = RESOLVED;
this.onResolvedCallbacks.forEach((fn) => fn());
}
};
let reject = (reason) => {
if (this.status === PENDING) {
this.reason = reason;
this.status = REJECTED;
this.onRejectedCallbacks.forEach((fn) => fn());
}
};
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
then(onFulfilled, onRejected) {
if (this.status === RESOLVED) {
onFulfilled(this.value);
}
if (this.status === REJECTED) {
onRejected(this.reason);
}
if (this.status === PENDING) {
this.onResolvedCallbacks.push(() => {
// todo...
onFulfilled(this.value);
});
this.onRejectedCallbacks.push(() => {
// todo...
onRejected(this.reason);
});
}
}
}
module.exports = Promise;