Home >Web Front-end >JS Tutorial >Why is `.then(success, fail)` Considered an Anti-pattern in Promise Handling?
In the Bluebird Promise documentation, .then(success, fail) is labeled as an antipattern. What's the reason behind this?
Unlike the recommended .then(success).catch(fail) chaining, using .then(success, fail) poses a control flow issue:
Using .then(success, fail):
try { results = some_call(); } catch (e) { logger.log(e); break then; } else logger.log(results);
Using .then(success).catch(fail):
try { var results = some_call(); logger.log(results); } catch (e) { logger.log(e); }
The antipattern is discouraged because it limits error handling to a single final catch handler. However, it can be useful in scenarios where:
To avoid repeating callbacks, you can use the following pattern:
some_promise_call() .catch(function(e) { return e; // it's OK, we'll just log it }) .done(function(res) { logger.log(res); });
Alternatively, you can leverage the .finally() method for this purpose.
The above is the detailed content of Why is `.then(success, fail)` Considered an Anti-pattern in Promise Handling?. For more information, please follow other related articles on the PHP Chinese website!