这个控制台输出什么?有没有谁能解释下为什么

var a = new Promise(function (res, rej) {
    rej(8);
});
a.then(
    function (val) {
        console.log(val + 2);
        return val + 1;
    },
    function (val) {
        console.log(val + 2);
        return val + 1;
    }
).catch(function (error) {
    console.log(error);
});
a.finally(function () {
    console.log("bb");
}).catch(function (d) {
    console.log(d);
});

这个控制台输出什么?有没有谁能解释下为什么
而且上图和下图的输出竟然不一样,实在懵了

var a = new Promise(function (res, rej) {
    rej(8);
}).then(
    function (val) {
        console.log(val + 2);
        return val + 1;
    },
    function (val) {
        console.log(val + 2);
        return val + 1;
    }
).catch(function (error) {
    console.log(error);
});
a.finally(function () {
    console.log("bb");
}).catch(function (d) {
    console.log(d);
});

图一

let a = new Promise((rew, rej) => {
    rej(1);
})
a.then(
    val => {
        console.log(1);
    }, val => {
        console.log(2);//2
    }).catch(res => {
    console.log(3);
})
a.finally(res => {
    console.log(4);//4
}).catch(res => {
    console.log(5);//5
})

Promise有两种写法:

  • new Promise().then(f1,f2);表示,成功时调用f1,失败时调用f2
  • new Promise().then(f1).catch(f2);表示,成功调用f1,失败调用f2
  • new Promise().then(f1,f2).catch(f3);你的写法,同时写的话,后面的catch里的回调方法不生效

图二

let a = new Promise((rew, rej) => {
    rej(1);
}).then(
    val => {
        console.log(1);
    }, val => {
        console.log(2);//2
    }).catch(res => {
    console.log(3);
})
a.finally(res => {
    console.log(4);//4
}).catch(res => {
    console.log(5);
})
  • 同理,catch()已经绑定输出2,后面再输出3的方法不生效,
  • 图一,promise:a是调用了2次,第一次:1没进,2生效,3不生效,第二次:重新绑定的回调函数,不受影响
  • 图二,promise:a在声明的时候就已经确定了:成功为1,失败为2,3不生效,在调用方法的时候,catch输出5也不生效。

复制代码不要贴图片