取消承诺与消息

时间:2017-06-20 16:53:26

标签: javascript angularjs promise angular-promise cancellation

在预先确定的情况下,我正在取消之前的通话,以防它尚未返回并使用以下代码进行了新的通话:

function($http, $window, $q, $timeout){

        var suggestions = [];
        var cancel = $q.defer();

        return {

            getSuggestions : function(inputText){

                var deferred =$q.defer();
                var promise = deferred.promise;

                cancel.resolve('request cancelled');
                cancel = $q.defer();
                var baseUrl = "http://localhost:8080/PackagingTest/hello";
                var params = {
                    query : inputText,
                    suggestionsSize : 10
                }

                $http.get(baseUrl, {params : params, timeout : cancel.promise}).then(
                    function(response){
                        suggestions = repsonse;
                        deferred.resolve(suggestions);
                    }, function(error){

                        //check if cancelled and log the error message
                        if(){
                                console.log(someErrorMsg);//should log 'request cancelled'
                        }
                        console.log(error);
                        deferred.reject(error);
                    });

                return promise;
            }

        }
    }

每次发出新请求时,都会取消上一个请求。但我无法获得取消状态消息。使用data: null, status: -1, config: Object, statusText: "", headers: function调用$ http错误处理程序,我找不到包含我的文本的任何属性。我做错了还是在请求中止时无法附加消息?

1 个答案:

答案 0 :(得分:0)

实际上无法将数据传递给catch上的abort处理程序。以下是onabort回调,内部角度使用:

  var requestError = function() {
    // The response is always empty
    // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
    completeRequest(callback, -1, null, null, '');
  };

completeRequest的定义是:

function completeRequest(callback, status, response, headersString, statusText) {...}