Callback Inversion in AngularJS: An Anti-Pattern
In AngularJS, it's common practice to pass callback functions to services that return Promises. However, this approach can introduce an anti-pattern and hinders the benefits of Promises.
Anti-Pattern Example:
Consider the following code, where the getTokens service accepts a callback function:
... getTokens: function(callbackFn) { $http.get('/api/tokens').then (function onFulfilled(response) { callbackFn(response.data); }); } ...
This approach has several disadvantages:
Refactoring for Best Practice:
To resolve this anti-pattern, refactor the code as follows:
... getTokens: function() { return $http.get('/api/tokens'); } ...
In the calling module, use the returned Promise to handle the result:
yourModule.getTokens() .then(function(response) { // handle it });
Benefits of Best Practice:
Adopting this best practice provides several advantages:
The above is the detailed content of Should You Use Callbacks with AngularJS Promises?. For more information, please follow other related articles on the PHP Chinese website!