【问题标题】:AngularJS Promise is not being cancelled when timeout called调用超时时,AngularJS Promise 不会被取消
【发布时间】:2019-04-21 16:48:15
【问题描述】:

我正在尝试实现一个简单的超时功能来兑现我的承诺。目标是如果我在 1 秒内没有收到响应,那么应该取消请求,即代码不应该等待响应,也不应该调用成功后的代码。在我看来,这似乎是非常简单的代码,但我不知道为什么它不起作用。以下是我的代码:

var canceler = $q.defer();
var timeoutPromise = $timeout(function() {
    canceler.resolve(); //abort the request when timed out
    console.log("Timed out");
    }, 1000);
$http.put(PutUrl, PurDataObject, {timeout: canceler.promise})
  .then(function(response){
        // control should never come here if the response took longer than 1 second
});

感谢任何帮助。我正在使用 AngularJS v1.5.5。

【问题讨论】:

    标签: javascript angularjs promise timeout


    【解决方案1】:

    无需使用$q.defer(),因为$timeout 服务已经返回了一个承诺:

    var timeoutPromise = $timeout(function() {
        console.log("Timed out");
        return "Timed out";
    }, 1000);
    
    $http.put(PutUrl, PurDataObject, {timeout: timeoutPromise})
      .then(function(response){
            // control should never come here if the response took longer than 1 second
    });
    

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2014-06-15
      相关资源
      最近更新 更多