你曾想过在 Promise
中,then()
和 catch()
的顺序会影响执行结果吗?
让我们通过两个代码片段来探讨这个问题。
代码片段 1
Promise.reject('failed')
.then(data => {
console.log('then', data)
})
.catch(err => {
console.log('catch:', err)
})
这个 Promise 的输出结果是:
catch: failed
代码片段 2
Promise.reject('failed')
.catch(err => {
console.log('catch:', err)
})
.then(data => {
console.log('then', data)
})
这个 Promise 的输出结果是:
catch: failed
then undefined
这种差异是由于 Promise
的链式调用特性造成的。在第一个 Promise
中,.then()
方法在 .catch()
方法之后调用,因此当 Promise
被 reject
时,会立即调用 .catch()
方法处理错误,并且后续的 .then()
方法不会执行。
在第二个 Promise
中,.catch()
方法在 .then()
方法之前调用。当 Promise
被 reject
时,会先执行 .catch()
方法处理错误,然后会继续执行后续的 .then()
方法。由于在 .catch()
中没有返回新的 Promise
对象或者抛出错误,所以后续的 .then()
方法中的数据值为 undefined
。