Home >Web Front-end >JS Tutorial >Why is `.then(success, fail)` an Antipattern in JavaScript Promises?
The Argument for Avoiding .then(success, fail)
The Bluebird promise FAQ advises against using .then(success, fail) as an antipattern. While try-catch blocks may seem analogous, there are differences:
Control Flow Differences:
.then(success, fail) returns a promise that will be rejected if the success callback throws an error. This means that if the success logger fails, the error will be passed to the .catch() callback, not the fail callback.
Control Flow Diagrams:
[Then with two arguments](https://i.sstatic.net/WAcpP.png)
[Then-catch chain](https://i.sstatic.net/wX5mr.png)
Synchronous Equivalent:
// then: { try ... catch(e) { ... } else ... } try { var results = some_call(); } catch(e) { logger.log(e); break then; } // else logger.log(results);
Handling Exceptions:
The .catch() logger will also handle exceptions from the success logger call, providing a more comprehensive error handling mechanism.
Anticipating the Antipattern's Usefulness
While the antipattern is generally discouraged, it can be useful when:
Caveat: Be aware that this approach introduces branching into the control flow.
Alternative to .then(success, fail)
To avoid code duplication, 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); });
Or you may opt for .finally() to handle both success and failure scenarios.
The above is the detailed content of Why is `.then(success, fail)` an Antipattern in JavaScript Promises?. For more information, please follow other related articles on the PHP Chinese website!