调用超时时不会取消AngularJS Promise

时间:2018-11-19 10:34:33

标签: javascript angularjs promise timeout

我正在努力实现一个简单的超时功能,以实现我的承诺。目标是如果我在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。

1 个答案:

答案 0 :(得分:0)

无需使用$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
});
相关问题