
Why Callbacks from Promise .then Methods are an Anti-Pattern
Question:
Is it an anti-pattern to provide callback functions to AngularJS services within promise .then methods? If so, how should the code be refactored and why?
Answer:
Re-factor the Code:
Change the getTokens method in the tokenService to return the promise directly instead of accepting a callback:
1 2 3 | var getTokens = function () {
return $http .get( '/api/tokens' );
};
|
Copy after login
In the controller, use the .then method to chain success/fail handlers:
1 2 3 4 | yourModule.getTokens()
.then( function (response) {
});
|
Copy after login
Why the Original Way was an Anti-Pattern:
-
Prevents further chaining of promise handlers. The original code prevents chaining additional .then methods for further processing of the response.
-
Inverts control. By accepting a callback, the control of processing the response is moved from the caller module to the called module, which is not ideal.
-
Unnecessary use of promises. While the $http service returns promises, the original code converts them back to callbacks, making the use of promises redundant.
-
Potential for confusion. Using promises as callbacks introduces an unnecessary concept into the codebase and can be difficult for team members to understand.
The above is the detailed content of Why are Callbacks in Promise .then Methods an Anti-Pattern in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!