$ http内的解决/拒绝承诺无法正常工作。

时间:2016-03-09 06:18:57

标签: javascript angularjs

我试图拒绝$ http.get调用中的延迟对象但是没有被正确拒绝。没有调用errorcallback,我只是想不通原因。 这基本上就是我所拥有的:

var promise = this.SomeAsyncCall(this.$.SomeID)
                .then(
                    function () 
                    {
                        service.SendAsyncDownloadReqeuest(someOtherID);
                    },
                this.ErrorHandler.HandleError)
                  .then(this._DownloadInitiated, this.ErrorHandler.HandleError);
              promise["finally"](this._DownloadRequestFinished);

这是service.SendAsyncDownloadRequest:

var SendAsyncDownloadReqeuest = function (ID)
{
    var url = "someUrl?ID=" + customerID;
    var navigator = self.$window.navigator;
    var window = self.$window;
    var deferred = self.$q.defer();
    self.$http.get(url, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {
        var success = false;
        //Initiate download via blob. Set success

        success ? deferred.resolve() : deferred.reject();
    })
    .error(function (data, status)
    {
        var error = 
        { 
           //Some error properties 
        }
        deferred.reject(error);
    });

    return deferred.promise;
};

当我通过从服务器返回500状态代码来测试它时,它到达http get调用的.error块并完成拒绝行,但是没有到达ErrorHandler的HandleError方法。 HandleError方法是正确的,因为它适用于在$ http.get不是任何东西中拒绝的promise的errorcallbacks。

2 个答案:

答案 0 :(得分:1)

您永远不会将service.SendAsyncDownloadReqeuest(someOtherID);的承诺传递回您的HandleError功能。您需要将代码更改为:

var promise = this.SomeAsyncCall(this.$.SomeID)
                .then(
                    function () 
                    {
                        return service.SendAsyncDownloadReqeuest(someOtherID);
                    },
                this.ErrorHandler.HandleError)
                  .then(this._DownloadInitiated, this.ErrorHandler.HandleError);
              promise["finally"](this._DownloadRequestFinished);

如果你想要更清楚一点,你可以改为:

var promise = this.SomeAsyncCall(this.$.SomeID)
                  .then(function () {
                         service.SendAsyncDownloadReqeuest(someOtherID).then(
                           this._DownloadInitiated,
                           this.ErrorHandler.HandleError);
                  },
                  this.ErrorHandler.HandleError);
promise["finally"](this._DownloadRequestFinished);

答案 1 :(得分:0)

不要使用成功方法。不推荐使用这两种方法。

  

$ http遗留承诺方法成功与错误   弃用。请改用标准方法。如果   $ httpProvider.useLegacyPromiseExtensions设置为false然后这些   方法将抛出$ http / legacy错误。

这是快捷方式

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

这是一个较长的GET方法示例

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Official Documentation

相关问题