聊聊Promise的值穿透和异常穿透。

5,208 阅读1分钟

值穿透

值穿透指的是,链式调用的参数不是函数时,会发生值穿透,就传入的非函数值忽略,传入的是之前的函数参数。

Promise.resolve(1)
    .then(2)
    .then(Promise.resolve(3))
    .then(console.log)

image.png
传入2或者promise的fulfilled状态都会发生值穿透。

Promise.resolve(1)
    .then(() => { return 2 })
    .then(() => { return 3 })
    .then(console.log)

image.png

Promise.resolve(1)
    .then(function () {
        return 2
    })
    .then(() => { Promise.resolve(3) })
    .then(console.log)

image.png
只有传入的是函数才会传递给下一个链式调用。

异常穿透

Promise.reject(1)
    .then(res => {
        console.log(res);
    })
    .then(res => { console.log(res) },
        rej => {
            console.log(`rej****${rej}`);
        })
    .catch(err => {
        console.log(`err****${err}`);
    })

image.png
当在then中传入了第二个函数,就不会被catch捕获到错误了。

Promise.reject(1)
    .then(res => {
        console.log(res);
    })
    .then(res => { console.log(res) },
        rej => {
            console.log(`rej****${rej}`);
        })
    .then(res => {
        console.log(`res****${res}`);
    }, rej => {
        console.log(`rej****${rej}`);
    })
    .catch(err => {
        console.log(`err${err}`);
    })

image.png
被then捕获的错误也会传给下一个链式调用成功的状态,虽然为undefined。


记录记录!