处理链式调用
howcode 2022-10-07 0 Promise
在真实的 Promise 中,我们可以这样调用.then
const p = new Promise((resolve, reject) => {
resolve(1);
});
p.then((res) => {
console.log(res); // 1
return 2;
}).then((res) => {
console.log(res); // 2
});
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
试想在我们手写的Promise
中,如何能链式调用呢?
核心要点
- 我们能够执行
.then
的前提是:p 为一个Promise
对象,所以,如果我们想实现链式调用的话,那就必须在上一个.then
中返回一个Promise
对象。因此,我们尝试在代码的then
函数中新增一个Promise
对象,并且返回出去 - 由于是
Promise
对象,所以下一个then
函数触发时,也必须是resolve
改变状态后才会被执行,故上一个.then
参数,要拿到上一个.then
回调返回值
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 = vareasonlue;
this.onRejectedCallbacks.forEach((fn) => fn());
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
// 新建一个Promise,并且返回
let p2 = new Promise((resolve, reject) => {
if (this.state === "fulfilled") {
// onFulfilled 成功的 .then 回调
let x = onFulfilled(this.value);
resolve(x);
}
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;
}
}
const p = new Promise((resolve, reject) => {
resolve(1);
});
p.then((res) => {
console.log(res);
return 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
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
如此以来,就完成了链式调用
评论
- 表情
——暂无评论——