【问题标题】:Cancel promise with message用消息取消承诺
【发布时间】:2017-11-23 08:17:12
【问题描述】:

在预先输入的情况下,我正在取消之前的调用,以防它尚未返回并且已经进行了新的调用,使用以下代码:

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;
            }

        }
    }

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

【问题讨论】:

标签: javascript angularjs promise angular-promise cancellation


【解决方案1】:

实际上无法将数据传递给abort 上的catch 处理程序。下面是 Angular 内部使用的 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) {...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 2018-12-10
    • 1970-01-01
    • 2015-01-23
    • 2015-02-13
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多