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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 22:15:13491browse

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

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

Bluebird's Promise FAQ suggests that using .then(success, fail) is an antipattern. This is because .then() calls return a promise that will be rejected if the callback throws an error. Consequently, when the success logger callback fails, the error is passed to the following .catch() callback but not to the fail callback provided alongside the success callback.

Control Flow Diagram:

[Image of control flow diagrams for then with two arguments and then catch chain]

Synchronous Equivalent:

// 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);
}

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

Pattern Rationale:

Usually, errors are caught in every step of the processing, and error handling is centralized so that all errors are handled by a single final handler. However, the pattern mentioned in the antipattern is useful when:

  • Errors need to be handled specifically in a given step.
  • If no error occurs, the subsequent action is significantly different.

This pattern can introduce branching in the control flow.

Recommended Pattern:

Instead of repeating the callback, consider using .catch() and .done():

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

You may also consider using .finally().

The above is the detailed content of When is Using `.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