Why are Callbacks from Promise `.then` Methods an Anti-Pattern

前端 未结 2 1905
日久生厌
日久生厌 2020-11-22 08:42

I have seen answers on StackOverflow where people suggest furnishing a callback function to an AngularJS service.

app.controller(\'tokenCtrl\', function($sco         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:36

    The code can be re-factored as follows:

    app.controller('tokenCtrl', function($scope, tokenService) {
        tokenService.getTokens.then ( callbackFn(tokens) {
            $scope.tokens = tokens;
        });
    });
    
    app.factory('tokenService', function($http) {
        var getTokens = function() {
            //return promise
            return $http.get('/api/tokens').then (function onFulfilled(response) {
                    //return tokens
                    return response.data;
                }
            );
        };
    
        return {
            getTokens: getTokens
        };
    });
    

    By having the service return a promise, and using the .then method of the promise, the same functionality is achieved with the following benefits:

    • The promise can be saved and used for chaining.

    • The promise can be saved and used to avoid repeating the same $http call.

    • Error information is retained and can be retrieved with the .catch method.

    • The promise can be forwarded to other clients.

提交回复
热议问题