Home >Web Front-end >JS Tutorial >When is `then(success, fail)` 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.
.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.
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.
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.
While the .then().catch() syntax provides better error handling, the .then(success, fail) antipattern can be useful in situations where you want to:
However, it's important to remember that this pattern introduces branching into the control flow, which may not be desirable in certain circumstances.
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!