【问题标题】:How to reject promise on d3 xhr request timeout?如何拒绝 d3 xhr 请求超时的承诺?
【发布时间】:2017-10-25 05:51:57
【问题描述】:

我想设置一个超时值,这样如果服务器在那个特定的时间范围内没有响应,那么 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!!'}) 

但它不起作用。

我正在使用承诺,所以我想在超时的情况下拒绝承诺。而且我想将它收到的相同值传递给 UI,以防我收到来自服务的错误。基本上是空值,以便它安定下来。但在超时的情况下,UI 不会收到任何值,并且我的屏幕加载程序会继续运行。

TIA。

【问题讨论】:

  • 哪个版本的 D3?我认为 Xhr 来自 v.3,但您链接到的文档是 v.4。
  • @Mark_M 我正在​​使用 3.5.5!但超时也适用!
  • @Manu 3.5.5 在 v4 中没有超时
  • @Cyril yup 刚刚注意到.. 在 3.5.5 中添加超时基本上会跳过请求,即使超时间隔为 20000 毫秒。早些时候用 200 毫秒尝试过,认为效果很好。但事实并非如此。我们可以通过其他方式使其在 3.5.5 中运行吗?

标签: javascript d3.js promise xmlhttprequest timeout


【解决方案1】:

由于 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 2018-04-06
    • 2013-06-22
    • 2018-02-11
    • 2021-11-02
    相关资源
    最近更新 更多