defer.promise在angularJS中返回相同的结果

时间:2017-03-09 19:00:07

标签: angularjs angular-promise deferred

我有一个从API获取数据的服务。当我尝试调用此服务时。它以相同的价值返回。

appName.service('FetchCustomerDate', ['$http', '$q', function($http, $q) {
    var self = this;
    self.getCustomerData = function(token,name) {
        var deferred = $q.defer();
        return $http({
            method: 'GET',
            url: ,
            headers: {
                "Authorization": token,
                "x-xcmc-auth": ''
            }
        }).then(function(response) {
            deferred.resolve(response);
            return deferred.promise;
        }, function(response) {
            deferred.reject(response);
            return deferred.promise;
        });
    };
}]);

2 个答案:

答案 0 :(得分:0)

我在这看到一点混乱。我们试着清除它。如果要使用延迟对象,则需要稍微更改一下代码:

appName.service('FetchCustomerDate', ['$http', '$q', function ($http, $q) {
    var self = this;
    self.getCustomerData = function (token, name) {
        var deferred = $q.defer();
        $http({ // Do not return  here, you need to return the deferred.promise
            method: 'GET',
            url: '...some URL here...',
            headers: {
                "Authorization": token,
                "x-xcmc-auth": ''
            }
        }).then(function (response) {
            deferred.resolve(response); // It's correct, you are resolving the deferred promise here.
            // return deferred.promise; // You do not need to return the deferred.promise here.
        }, function (response) {
            deferred.reject(response); // It's correct, you are rejecting the deferred promise here.
            // return deferred.promise; // You do not need to return the deferred.promise here.
        });

        return deferred.promise; // The function must return the deferred.promise
    };
}]);

详细信息,函数getCustomerData必须返回属于deferred对象return deferred.promise的承诺。在then()内部回调您只需解决或拒绝deferred承诺。您无需返回deferred.promise

您可以改进代码。 $http服务返回一个promise,then回调返回的值由promise中的then方法包装。知道这一点,您可以删除deferred对象的使用:

appName.service('FetchCustomerDate', ['$http', function ($http) {
    var self = this;
    self.getCustomerData = function (token, name) {
        return $http({ // Here, you need to return the promise returned by $http. Than promise will contain the response returned inside "then" callbacks.
            method: 'GET',
            url: '...some URL here...',
            headers: {
                "Authorization": token,
                "x-xcmc-auth": ''
            }
        }).then(function (response) {
            return response; // Simply return the response, it will be wrapped in a resolved promise by "then()"
        }, function (response) {
            return response; // Simply return the response, it will be wrapped in a rejected promise by "then()"
        });
    };
}]);

如您所见,2 then个回调只返回response对象,因此您可以省略它们:

appName.service('FetchCustomerDate', ['$http', function ($http) {
    var self = this;
    self.getCustomerData = function (token, name) {
        return $http({ // Here, you need to return the promise returned by $http. Than promise will contain the response form the GET call
            method: 'GET',
            url: '...some URL here...',
            headers: {
                "Authorization": token,
                "x-xcmc-auth": ''
            }
        });
    };
}]);

答案 1 :(得分:0)

通常,当您使用$http服务获取数据时,您希望从响应中获取数据并将其影响到$scope,或以某种方式处理它。你想做什么?请澄清你的问题。

通常,抓取会看起来像这样:

appName.service('FetchCustomerDate', ['$http', '$q', function($http, $q) {
    var self = this;

    function notifyError(reason) {
      console.error(reason);
    }

    self.getCustomerData = function(token,name) {
        var deferred = $q.defer();
        return $http({
            method: 'GET',
            url: ,
            headers: {
                "Authorization": token,
                "x-xcmc-auth": ''
            }
        })
          .then(function onSuccess(response) {
            var cfg = response.data; // process data 
        })
          .then(function onSuccess(response) {
            // chained promises
        })
          .then(
            function onSuccess(res) {
              // ... this will trigger the chain reaction
              deferred.resolve(res);
            },
            function onFailure(reason) {
              notifyError(reason); // manage the error
              deferred.reject(reason);
            })
          ;
          return deferred.promise;
        }
    }]);