Home >Web Front-end >JS Tutorial >When is Using `.then(success, fail)` 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:
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!