一直以来有个误解,以为then和catch的执行就是一个二选一的过程,直到后来遇到类似下面的代码,发现不是这么一回事
Promise.reject().then(() => {
console.log('1-1')
}).catch(() => {
console.log('1-2')
})
Promise.resolve().then(() => {
console.log('2-1')
}).catch(() => {
console.log('2-2')
})
执行结果自然是2-1 1-2
翻了一下then和catch文档,catch是then的语法糖,catch(fn) 就是then(undefined, fn)
而Promise.prototype.then(arg1, arg2)
两个参数都是可选,如果arg1是undefined,而promise状态是fullfilled
那么arg1就相当于 x => x
如果arg2是undefined,promise的状态是rejected,那么arg2是一个‘thrower’
(MDN原文),结果应该就是throw error的意思
总之就是遇到参数为空的情况下,状态往下顺延。
所以每一个then和catch都会执行,因此,才会代码才会产生上面的运行结果。
总结,有时间,看源码,没时间,看文档,才能正确理解