gpt4 book ai didi

javascript - 如何拒绝 d3 xhr 请求超时的 promise ?

转载 作者:行者123 更新时间:2023-11-30 14:58:11 25 4
gpt4 key购买 nike

我想设置一个超时值,这样如果服务器在那个特定的时间范围内没有响应,那么 UI 应该继续前进而不是等待响应。到目前为止,我使用了以下语法,但 UI 在等待响应时被挂起。如何指定回调以重置值并通知 UI 不再需要等待。

q.promise(function(resolve, reject) {
d3.xhr(my_url)
.header('Content-Type', 'text/xml')
.timeout(2000)
.send(this.my_method, my_xmlData, function(error, data) {
})
});

我读了here d3 xhr 现在支持超时功能。我如何使用它并在请求超时时执行回调?谁能告诉我如何正确使用它?我尝试使用

.ontimeout(function(){console.log('request timedout!!'}) 

但是没有用。

我正在使用 promise ,所以我想在超时的情况下拒绝 promise 。我想向 UI 传递它接收到的相同值,以防我从服务中收到错误。基本上为空值,以便它安定下来。但在超时的情况下,UI 不会收到任何值,我的屏幕加载程序会继续运行。

TIA。

最佳答案

由于d3 v3不支持超时,可以这样超时:

var url = "https://mysafeinfo.com/api/data?list=englishmonarchs&format=xml";
let pr = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'document';
xhr.overrideMimeType('text/xml');
xhr.open('GET', url, true);
xhr.timeout = 1; // time in milliseconds
xhr.onload = function(d) {
console.log("load", xhr.responseXML)
resolve(xhr.responseXML)
};

xhr.ontimeout = function(e) {
console.log("timeout")
reject({message: "I got timed out"});
};

xhr.send(null);
});
pr.then(function(data) {
console.log(data)
}, function(err) {
console.log(err)
})

给出更高的超时工作代码here

如果你使用 d3.v4,你可以使用超时工作代码 here

关于javascript - 如何拒绝 d3 xhr 请求超时的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46924863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com