Search code examples
javascriptes6-promise

why to use Promise.catch() instead of Promise.then()


I have a rejected promise somewhere in my promise chain like this. I know following code will work similarly.

let promise = Promise.resolve(3);
let p1 = promise.then(() => 2)
                .then(() => {throw 'some error'})
                .then(null, (err) => {console.log(err)})


let p2 = promise.then(() => 2)
                .then(() => {throw 'some error'})
                .catch((err) => {console.log(err)})

Is there any difference conceptually in chaining promises with .then(null, (error) {}) instead of just .catch((err) => {})


Solution

  • Promise.catch() is equal to Promise.then(null, callback). You can use these interchangably. However Promise.catch is more descriptive and has the following advantages:

    1. Easier to know that it is a error handling mechanism when you read .catch than when you read .then(null, callback)
    2. Actually less code because you can leave out the null as a first argument of .then()

    To conclude, there is no functional difference. However, .catch() is more descriptive and less code and thus superior.

    As for the promise chaining it doesn't have any effect as they are functionally similar.