根据MDN文档,then() 和 catch() 方法会立即返回一个待定(pending)的 Promise。如果处理函数没有返回任何值,则返回的 Promise 将以 undefined 值变为已履行(fulfilled)。假设当前的 Promise 是 P0,那么直接附加到 P0 的 then() 返回 Promise P1,而 catch() 也直接附加到 P0 返回 Promise P2。最初时,P1 和 P2 都处于 "pending" 状态。现在,如果 catch() 的处理器运行,P2 将变为已履行状态并带有 undefined 值。由于 then() 的处理器未执行,那么 P1 是否将始终处于 "pending" 状态呢?如果不是,那么其状态为何会发生变化,又是如何改变的?(控制代码流程的状态变化机制是怎样的?)
代码:
const p0 = new Promise((resolve, reject) => {
let num = Math.random();
setTimeout(() => {
if (num >= 0.5) {
console.log("Resolved");
resolve("Promise resolved");
} else {
console.log("Rejected");
reject("Promise rejected");
}
}, 7000);
});
const p1 = p0.then(function (resolveValue) {
console.log("Then handler was executed");
console.log(resolveValue);
});
console.log("P1");
console.log(p1);
const p2 = p0.catch((rejectValue) => {
console.log("Catch handler was executed");
console.log(rejectValue);
});
console.log("P2");
console.log(p2);
setTimeout(() => {
console.log("P1");
console.log(p1);
}, 12000);
setTimeout(() => {
console.log("P2");
console.log(p2);
}, 17000);
输出:
P1
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
P2
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
Rejected
Catch handler was executed
Promise rejected
Uncaught (in promise) Promise rejected
Promise.then (async)
(anonymous) @ app2.js:15
P1
Promise {<rejected>: 'Promise rejected'}
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: "Promise rejected"
P2
Promise {<fulfilled>: undefined}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined