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

  1. Home
  2. javascript
  3. When is .then(success, fail) considered an antipattern for promises?

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 this 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 as the correctly way.

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

What’s the difference?

First answer

Second answer

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

Third answer

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)
Reprint:https://stackoverflow.com/questions/24662289/when-is-thensuccess-fail-considered-an-antipattern-for-promises
Spread the love

Related articles

Comments are closed.