Angular $http:在“超时"配置上设置承诺 [英] Angular $http : setting a promise on the 'timeout' config
问题描述
在 Angular $http
文档中,它提到你可以将超时"配置设置为数字或承诺.
In the Angular $http
docs, it mentions that you can set the 'timeout' config to either a number or a promise.
timeout – {number|Promise} – 以毫秒为单位的超时,或承诺解决后应中止请求.
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
但我不确定如何使用承诺来完成这项工作.我如何设置一个数字和一个承诺?基本上,我希望能够知道 http 调用(承诺)是否由于超时"或其他原因而出错.我需要能够分辨出差异.感谢您的帮助!!!
But I am not sure how to make this work using a promise. how do i set a number and a promise ? Basically I want to be able to know whether an http call (promise) errored due to a 'timeout' or something else. I need to be able to tell the difference. Thanks for any help !!!
推荐答案
此代码来自 $httpBackend 源代码:
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (timeout && timeout.then) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
status = ABORTED;
jsonpDone && jsonpDone();
xhr && xhr.abort();
}
timeout.then(timeoutRequest)
表示当promise被解析(不是拒绝)timeoutRequest被调用,xhr请求被中止.
timeout.then(timeoutRequest)
means that when the promise is resolved (not rejected) timeoutRequest is invoked and xhr request is aborted.
如果请求超时,则reject.status === 0
(注意:在网络故障的情况下,reject.status
也将是等于 0),示例:
If the request was timeout then reject.status === 0
(Note: in case of a network failure, then reject.status
will also be equals to 0), An example:
app.run(function($http, $q, $timeout){
var deferred = $q.defer();
$http.get('/path/to/api', { timeout: deferred.promise })
.then(function(){
// success handler
},function(reject){
// error handler
if(reject.status === 0) {
// $http timeout
} else {
// response error status from server
}
});
$timeout(function() {
deferred.resolve(); // this aborts the request!
}, 1000);
});
这篇关于Angular $http:在“超时"配置上设置承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!