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
Release: 2024-12-25 18:42:14
Original
884 people have browsed it

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);
Copy after login

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

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

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);
   });
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template