When is .then(success, fail) considered an antipattern for promises?

Javascriptnode.jsPromiseBluebird

Javascript Problem Overview


I had a look at the bluebird promise FAQ, in which it mentions that .then(success, fail) is an antipattern. I don't quite understand its explanation as for the try and catch. What's wrong with the following?

some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })

It seems that the example is suggesting the following to be the correct way.

some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })

What's the difference?

Javascript Solutions


Solution 1 - Javascript

> What's the difference?

The .then() call will return a promise that will be rejected in case the callback throws an error. This means, when your success logger fails, the error would be passed to the following .catch() callback, but not to the fail callback that goes alongside success.

Here's a control flow diagram:

control flow diagram of then with two arguments control flow diagram of then catch chain

To express it in synchronous code:

// some_promise_call().then(logger.log, logger.log)
then: {
    try {
        var results = some_call();
    } catch(e) {
        logger.log(e);
        break then;
    } // else
        logger.log(results);
}

The second log (which is like the first argument to .then()) will only be executed in the case that no exception happened. The labelled block and the break statement feel a bit odd, this is actually what python has try-except-else for (recommended reading!).

// some_promise_call().then(logger.log).catch(logger.log)
try {
    var results = some_call();
    logger.log(results);
} catch(e) {
    logger.log(e);
}

The catch logger will also handle exceptions from the success logger call.

So much for the difference.

> I don't quite understand its explanation as for the try and catch

The argument is that usually, you want to catch errors in every step of the processing and that you shouldn't use it in chains. The expectation is that you only have one final handler which handles all errors - while, when you use the "antipattern", errors in some of the then-callbacks are not handled.

However, this pattern is actually very useful: When you want to handle errors that happened in exactly this step, and you want to do something entirely different when no error happened - i.e. when the error is unrecoverable. Be aware that this is branching your control flow. Of course, this is sometimes desired.


> What's wrong with the following? > > some_promise_call() > .then(function(res) { logger.log(res) }, function(err) { logger.log(err) })

That you had to repeat your callback. You rather want

some_promise_call()
   .catch(function(e) {
       return e; // it's OK, we'll just log it
   })
   .done(function(res) {
       logger.log(res);
   });

You also might consider using .finally() for this.

Solution 2 - Javascript

The two aren't quite identical. The difference is that the first example won't catch an exception that's thrown in your success handler. So if your method should only ever return resolved promises, as is often the case, you need a trailing catch handler (or yet another then with an empty success parameter). Sure, it may be that your then handler doesn't do anything that might potentially fail, in which case using one 2-parameter then could be fine.

But I believe the point of the text you linked to is that then is mostly useful versus callbacks in its ability to chain a bunch of asynchronous steps, and when you actually do this, the 2-parameter form of then subtly doesn't behave quite as expected, for the above reason. It's particularly counterintuitive when used mid-chain.

As someone who's done a lot of complex async stuff and bumped into corners like this more than I care to admit, I really recommend avoiding this anti-pattern and going with the separate handler approach.

Solution 3 - Javascript

By looking at advantages and disadvantages of both we can make a calculated guess as to which is appropriate for the situation. These are the two main approaches to implementing promises. Both have it's pluses and minus

Catch Approach

some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })

Advantages

  1. All errors are handled by one catch block.
  2. Even catches any exception in the then block.
  3. Chaining of multiple success callbacks

Disadvantages

  1. In case of chaining it becomes difficult to show different error messages.

Success/Error Approach

some_promise_call()
.then(function success(res) { logger.log(res) },
      function error(err) { logger.log(err) })

Advantages

  1. You get fine grained error control.
  2. You can have common error handling function for various categories of errors like db error, 500 error etc.

Disavantages

  1. You will still need another catch if you wish to handler errors thrown by the success callback

Solution 4 - Javascript

Simple explain:

In ES2018

> When the catch method is called with argument onRejected, the > following steps are taken: > > 1. Let promise be the this value. > 2. Return ? Invoke(promise, "then", « undefined, onRejected »).

that means:

promise.then(f1).catch(f2)

equals

promise.then(f1).then(undefiend, f2)

Solution 5 - Javascript

Using .then().catch() lets you enable Promise Chaining which is required to fulfil a workflow. You may need to read some information from database then you want to pass it to an async API then you want to manipulate the response. You may want to push the response back into the database. Handling all these workflows with your concept is doable but very hard to manage. The better solution will be then().then().then().then().catch() which receives all errors in just once catch and lets you keep the maintainability of the code.

Solution 6 - Javascript

Using then() and catch() helps chain success and failure handler on the promise.catch() works on promise returned by then(). It handles,

  1. If promise was rejected. See #3 in the picture
  2. If error occurred in success handler of then(), between line numbers 4 to 7 below. See #2.a in the picture (Failure callback on then() does not handle this.)
  3. If error occurred in failure handler of then(), line number 8 below. See #3.b in the picture.

`

  1. let promiseRef: Promise = this. aTimetakingTask (false);
  2. promiseRef
  3.  .then( 
    
  4.  (result) => {
    
  5.     /* successfully, resolved promise.
    
  6.        Work on data here */ 
    
  7.  },
    
  8.  (error) => console.log(error)
    
  9.  )
    
  10. .catch( (e) => {
    
  11.     /* successfully, resolved promise.
    
  12.        Work on data here */ 
    
  13.  });`
    

enter image description here

> Note: Many times, failure handler might not be defined if catch() is > written already. > EDIT: reject() result in invoking catch() only if the error > handler in then() is not defined. Notice #3 in the picture to > the catch(). It is invoked when handler in line# 8 and 9 are not > defined.

It makes sense because promise returned by then() does not have an error if a callback is taking care of it.

Solution 7 - Javascript

Instead of words, good example. Following code (if first promise resolved):

Promise.resolve()
.then
(
  () => { throw new Error('Error occurs'); },
  err => console.log('This error is caught:', err)
);

is identical to:

Promise.resolve()
.catch
(
  err => console.log('This error is caught:', err)
)
.then
(
  () => { throw new Error('Error occurs'); }
)

But with rejected first promise, this is not identical:

Promise.reject()
.then
(
  () => { throw new Error('Error occurs'); },
  err => console.log('This error is caught:', err)
);

Promise.reject()
.catch
(
  err => console.log('This error is caught:', err)
)
.then
(
  () => { throw new Error('Error occurs'); }
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2127480View Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow
Solution 2 - JavascriptacjayView Answer on Stackoverflow
Solution 3 - JavascriptaWebDeveloperView Answer on Stackoverflow
Solution 4 - JavascriptbytefishView Answer on Stackoverflow
Solution 5 - JavascriptJayant VarshneyView Answer on Stackoverflow
Solution 6 - JavascriptVenkeyView Answer on Stackoverflow
Solution 7 - JavascriptktretyakView Answer on Stackoverflow