Home > Web Front-end > JS Tutorial > Why are Callbacks in Promise .then Methods an Anti-Pattern in AngularJS?

Why are Callbacks in Promise .then Methods an Anti-Pattern in AngularJS?

Patricia Arquette
Release: 2024-11-16 07:41:03
Original
832 people have browsed it

Why are Callbacks in Promise .then Methods an Anti-Pattern in AngularJS?

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:

var getTokens = function() {
  return $http.get('/api/tokens');
};
Copy after login

In the controller, use the .then method to chain success/fail handlers:

yourModule.getTokens()
  .then(function(response) {
    // handle it
  });
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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template