Search code examples
javascriptpromisees6-promise

Is Promise.then(a, b) the same as Promise.then(a).catch(b)?


What are the differences between

?

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?


Solution

  • 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().

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

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

    Using the then(a,b) style you can't:

    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.

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