Search code examples
javascriptpromisees6-promise

What is the difference between doing `<..>.get().then().then().catch().finally()` vs `<...>.get().then().catch().then().finally`


I am learning a bit about promises in Javascript and am wondering if there is any difference when reordering in the following way <...>.get().then().then().catch().finally() vs <...>.get().then().catch().then().finally()?


Solution

  • With the following chain

    <...>.get().then().then().catch().finally()
    

    catch method will handle the rejection of all the previous promises in the chain, whereas with the following chain

    <...>.get().then().catch().then().finally()
    

    catch method will not handle the rejection of promise returned by the last then method.

    This kind of chain is useful when you want to handle a promise rejection and turn it into fulfilment of the promise returned by the catch method to allow the promise chain to continue.

    If the resulting promise of the 2nd chain is used somewhere or if you are returning the promise at the end of this chain from a function as shown below,

    function foo() {
      return <...>.get().then().then().catch().finally();
    }
    

    then not using another catch method is fine because in that case, the code that calls this function can handle the promise rejection that wasn't caught and handled by the promise chain itself.

    However, if that's not the case, then you should definitely have a 2nd catch method after the last then method call as well.