Home >Web Front-end >JS Tutorial >When is `then(success, fail)` an Antipattern for Promises?

When is `then(success, fail)` an Antipattern for Promises?

DDD
DDDOriginal
2024-12-22 06:07:12607browse

When is `then(success, fail)` an Antipattern for Promises?

When is .then(success, fail) Considered an Antipattern for Promises?

The .then(success, fail) syntax in promises can be seen as an antipattern in some cases. Let's explore the reasons and compare it with the .then().catch() approach.

Control Flow Differences

.then(success, fail) returns a promise that rejects if the callback function throws an error. Thus, if the success logger fails, the error will be passed to the subsequent .catch() handler, not the fail callback.

Antipattern Scenario

In the following scenario, using .then(success, fail) becomes problematic:

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

If the success logging function fails, the error won't be caught by the fail callback, but by the next .catch() handler in the chain. This can disrupt the intended error handling logic.

Prefer .then().catch()

Instead, the recommended approach is to use .then() and .catch() separately:

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

In this case, the .catch() handler will also catch any errors thrown by the success logging function. This ensures all errors are handled in a consistent manner.

Exception Handling Intent

While the .then().catch() syntax provides better error handling, the .then(success, fail) antipattern can be useful in situations where you want to:

  • Handle errors specifically in a given step.
  • Take different actions based on whether an error occurred or not.

However, it's important to remember that this pattern introduces branching into the control flow, which may not be desirable in certain circumstances.

Alternative Options

Instead of .then(success, fail), the .done() or .finally() methods can be used to handle completion or errors consistently.

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

// Handle completion always, regardless of errors
some_promise_call()
   .finally(function() {
       logger.log('Promise completed');
   });

The above is the detailed content of When is `then(success, fail)` an Antipattern for Promises?. 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