为什么从 Promise (p2) 中删除 catch() 结果按预期运行,但保留 catch() 流程却不同?然而,Promise(p2)中的catch()并没有被执行。不知道我误会了什么...
const onFinally_1 = () => {
console.log('Promise settled! 1');
i++;
};
const onFinally_3 = () => console.log('Promise settled! 3');
const p1 = new Promise((resolve, reject) => {
resolve(1);
})
.then(
(res) => Promise.resolve(onFinally_1()).then(() => res),
(err) => Promise.resolve(onFinally_1()).then(() => { throw err; })
)
.then((result) => console.log(result), (x) => { console.log('B'); throw x; })
.catch((error) => console.log('=>', error))
const p2 = new Promise((resolve, reject) => {
resolve(3);
})
.then((result) => console.log(result))
// .catch((error) => console.log(error))
.then(
(res) => Promise.resolve(onFinally_3()).then(() => res),
(err) => Promise.resolve(onFinally_3()).then(() => { throw err; })
)
结果:
Promise settled! 1
3
B
Promise settled! 3
ReferenceError: i is not defined...
const onFinally_1 = () => {
console.log('Promise settled! 1');
i++;
};
const onFinally_3 = () => console.log('Promise settled! 3');
const p1 = new Promise((resolve, reject) => {
resolve(1);
})
.then(
(res) => Promise.resolve(onFinally_1()).then(() => res),
(err) => Promise.resolve(onFinally_1()).then(() => { throw err; })
)
.then((result) => console.log(result), (x) => { console.log('B'); throw x; })
.catch((error) => console.log(error))
const p2 = new Promise((resolve, reject) => {
resolve(3);
})
.then((result) => console.log(result))
.catch((error) => console.log(error))
.then(
(res) => Promise.resolve(onFinally_3()).then(() => res),
(err) => Promise.resolve(onFinally_3()).then(() => { throw err; })
)
结果:
Promise settled! 1
3
B
ReferenceError: i is not defined...
Promise settled! 3
then
和 catch
创建新的承诺,从而创建新的微任务,所以基本上这里有来自 p1
和 p2
的并行微任务链。一旦从 catch
中删除 p2
,就会使 p2
的微任务链变短,因此输出的顺序会发生变化。