我正在尝试为我的承诺实现一个简单的超时功能。目标是,如果我在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。
无需使用$q.defer()
,因为$timeout
服务已经返回promise:
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
});