Home >Web Front-end >JS Tutorial >Why is `.then(success, fail)` Considered an Anti-pattern in Promise Handling?

Why is `.then(success, fail)` Considered an Anti-pattern in Promise Handling?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 18:42:14809browse

Why is `.then(success, fail)` Considered an Anti-pattern in Promise Handling?

Drawbacks of Using .then(success, fail) for Promise Handling

Question:

In the Bluebird Promise documentation, .then(success, fail) is labeled as an antipattern. What's the reason behind this?

Answer:

Unlike the recommended .then(success).catch(fail) chaining, using .then(success, fail) poses a control flow issue:

  • If there's an error in the success callback, it is propagated to the next .catch() handler, effectively skipping the fail callback.

Comparison of Control Flows:

Using .then(success, fail):

try {
    results = some_call();
} catch (e) {
    logger.log(e);
    break then;
} else
    logger.log(results);

Using .then(success).catch(fail):

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

Rationale:

The antipattern is discouraged because it limits error handling to a single final catch handler. However, it can be useful in scenarios where:

  • You want to handle errors in a specific callback step.
  • You require different handling for error and non-error cases (branching the control flow).

Refinement:

To avoid repeating callbacks, you can use the following pattern:

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

Alternatively, you can leverage the .finally() method for this purpose.

The above is the detailed content of Why is `.then(success, fail)` Considered an Anti-pattern in Promise Handling?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn