AngularJS 调用超时时未取消 Promise
AngularJS Promise is not being cancelled when timeout called
我正在尝试实现一个简单的超时功能以实现我的承诺。目标是如果我在 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
服务已经 returns 承诺:
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
});
我正在尝试实现一个简单的超时功能以实现我的承诺。目标是如果我在 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
服务已经 returns 承诺:
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
});