javascript – Promise.then(a,b)和Promise.then(a).catch(b)一样吗?

参见英文答案 > When is .then(success,fail) considered an antipattern for promises?5个
有什么区别

>

07001.then(a,b)

>

07001.then(a).catch(b)

无论myPromise的内容和状态以及函数a和b的实现如何,两个JavaScript表达式总是会产生相同的结果吗?

除了代码可读性之外,我是否应该更喜欢使用一个而不是另一个?

解决方法

它们处理then()回调中的错误的方式不同,在某些情况下,这可能是一个非常显着的差异,大多数人建议只使用catch().

例如,使用catch(),您可以捕获此错误:

Promise.resolve('test')
.then(r => {
  throw("whoops")
})
.catch(e => console.log("caught error:",e))

使用then(a,b)样式你不能:

Promise.resolve('test')
.then(r => { throw("whoops")},e => console.log("caught error?",e))
// unhandled rejection (you'll need to look in the console)

除了一些测试场景之外,很难想到这种行为首选的用例.

您可以使用两者,这将在then()回调中捕获拒绝和错误,但这会使您比您可能需要的更令人困惑,除非您有一个特殊用例来区分这两种错误.例如哪个处理程序处理哪些错误:

Promise.reject("rejected")
.then(r => {throw("whoops")},e => console.log("Promise 1: caught error in second function:",e))
.catch(e=> console.log("Promise 1: caught error in catch",e))

Promise.resolve("rejected")
.then(r => {throw("whoops")},e => console.log("Promise 2: caught error in second function:",e))
.catch(e=> console.log("Promise 2: caught error in catch",e))

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小