Promise.then(a,b)与Promise.then(a).catch(b)相同吗? [英] Is Promise.then(a, b) the same as Promise.then(a).catch(b)?

查看:160
本文介绍了Promise.then(a,b)与Promise.then(a).catch(b)相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


myPromise.then(a, b)


  • myPromise.then(a).catch(b)


  • 两个JavaScript表达式是否总是产生相同的结果,而不管 myPromise的内容和状态如何以及函数 a b 的实现?

    Do the two JavaScript expressions always yield the same result, regardless of the content and state of myPromise and implementations of functions a and b?

    除了代码可读性之外,还有什么情况比我更喜欢使用一种?

    Is there any situation where I should prefer using one over the other, other than code readability?

    推荐答案

    这些是在 then()回调中处理错误的方式有所不同,在某些情况下,这可能是一个足够大的差异多数人建议只使用 catch()

    These are different in the way they handle errors in the then() callback, which in some cases can be a significant enough difference that most people recommend only using catch().

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

    For example with catch(), you can catch this error:

    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)

    除了某些测试方案外,很难想到一个使用这种行为的用例。

    Other than some testing scenarios, it's hard to think of a use case where this behavior would be preferred.

    您可以同时使用它们,这将在 then()回调中捕获拒绝和错误,但这会使事情比您可能需要的更加混乱,除非您有一个特殊的用例来区分这两种错误。例如,哪个处理程序处理哪些错误:

    You can use both, which will catch rejections and errors in the then() callback, but this makes things more confusing than you probably need unless you have a special use case for distinguishing between these two kinds of errors. For example which handler handles which errors:

    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))

    这篇关于Promise.then(a,b)与Promise.then(a).catch(b)相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆