处理不同的情况
howcode 2022-10-07 0 Promise
通常情况下,我们在.then
时返回的时一个Promise
对象,而不是向上节案例中的 return 2
;
p.then((res) => {
console.log(res);
return new Promise((resolve, reject) => {
resolve(2);
});
}).then((res) => {
console.log(res); // Promise
});
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
此时在下一个 .then
的时候,打印出来的结果是一个Promise
对象
原因
let x = onFulfilled(this.value); // 得到一个Promise
resolve(x); // 没做任何处理直接返回
1
2
2
分析情况
- 如果是一个普通值,直接调用
resolve
- 如果是
Promise
对象,看Promise
是成功还是失败 如果成功resolve
;如果失败reject
- 在很多地方都需要进行该返回值的判断处理,因此将该方法封装起来
class Promise {
constructor(executor) {
this.state = "pending";
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
let resolve = (value) => {
if (this.state === "pending") {
this.state = "fulfilled";
this.value = value;
this.onResolvedCallbacks.forEach((fn) => fn());
}
};
let reject = (reason) => {
if (this.state === "pending") {
this.state = "rejected";
this.reason = reason;
this.onRejectedCallbacks.forEach((fn) => fn());
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
let p2 = new Promise((resolve, reject) => {
if (this.state === "fulfilled") {
let x = onFulfilled(this.value);
resolvePromise(x, resolve, reject);
}
if (this.state === "rejected") {
onRejected(this.reason);
}
if (this.state === "pending") {
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value);
});
this.onRejectedCallbacks.push(() => {
onRejected(this.reason);
});
}
});
return p2;
}
}
function resolvePromise(x, resolve, reject) {
// 如果是Promise对象
if (x instanceof Promise) {
x.then(
(value) => {
// 成功时进行resolve的回调
resolve(value);
},
(err) => {
// 失败时进行reject的回调
reject(err);
}
);
} else {
resolve(x);
}
}
const p = new Promise((resolve, reject) => {
resolve(1);
});
p.then((res) => {
console.log(res);
return new Promise((resolve, reject) => {
resolve(2);
});
}).then((res) => {
console.log(res);
});
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
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
评论
- 表情
——暂无评论——