很难理解 JavaScript 中 Promise 的 catch() 的行为

问题描述 投票:0回答:1

为什么从 Promise (p2) 中删除 catch() 结果按预期运行,但保留 catch() 流程却不同?然而,Promise(p2)中的catch()并没有被执行。不知道我误会了什么...

  • 从 Promise 中删除catch() (p2)

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...
  • keeping 从 Promise 中 catch() (p2)

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
javascript promise
1个回答
0
投票

then
catch
创建新的承诺,从而创建新的微任务,所以基本上这里有来自
p1
p2
的并行微任务链。一旦从
catch
中删除
p2
,就会使
p2
的微任务链变短,因此输出的顺序会发生变化。

© www.soinside.com 2019 - 2024. All rights reserved.