处理循环调用的问题
howcode 2022-10-07 0 Promise
提示
此时,代码已经相对完整,但是仍然存在循环调用的问题
在真实的Promise
中,我们按以下方式调用:
const p = new Promise((resolve, reject) => {
resolve(1);
});
const p2 = p.then((res) => {
console.log(res);
return p2;
});
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
运行时会发现抛Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>
异常,这是因为 p2 需要接收p.then
的结果,而 p2 又作为p.then
的结果返回,如此便陷入了死循环
但是Promise
给我们做了这块异常处理,所以我们也需要在我们的代码中处理这块的异常
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") {
// 设置定时器的原因是在上面过程中,p2还没创建完毕,故需要开启定时器,等p2创建完成才能传值过去
setTimeout(() => {
let x = onFulfilled(this.value);
resolvePromise(x, resolve, reject, p2); //将p2传进去
}, 0);
}
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, p2) {
// 将x和p2对比,如果相同则抛出异常
if (x === p2) {
return reject(
new TypeError(
"Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>"
)
);
}
if (x instanceof Promise) {
x.then(
(value) => {
resolve(value);
},
(err) => {
reject(err);
}
);
} else {
resolve(x);
}
}
const p = new Promise((resolve, reject) => {
resolve(1);
});
const p2 = p.then((res) => {
return p2;
});
p2.then(
() => {},
(err) => {
console.log(err);
}
);
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
80
81
82
83
84
85
86
87
88
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
80
81
82
83
84
85
86
87
88
评论
- 表情
——暂无评论——