【问题标题】:JS fetch downloading a file: Where to place the spinner?JS fetch 下载文件:在哪里放置微调器?
【发布时间】:2020-06-12 20:53:15
【问题描述】:

我正在尝试使用 fetch 下载文件,我正在尝试放置一个微调器,但每次我放置它时,fetch 都会失败。

    document.getElementById("loader").style.display = 'block';

    fetch(url)
        .then(resp => resp.blob())
        .then(file => {
            if (file.size > 0) {
                const url = window.URL.createObjectURL(file);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            } else {
                $('#banner').html('<div class="alert alert-warning" role="alert">This provider does not seem to have any data during the selected dates, if you believe there is an issue, please contact the developers</div>');
            }
              document.getElementById("loader").style.display = 'none';

        })
        .catch(() => {
            $('#banner').html('<div class="alert alert-warning" role="alert">This provider does not seem to have any data during the selected dates, if you believe there is an issue, please contact the developers</div>');
            document.getElementById("loader").style.display = 'none';

        });

微调器是document.getElementById("loader"),我在生产代码中将其注释掉,因为它会导致获取失败。

如果您单击下载,它将开始提取并且微调器可见,然后在一段时间后提取失败,没有文件下载并且微调器消失。如果您注释掉微调器,一切正常。

我收到此错误500 internal server error

而这个momentjs警告是无关紧要的。

moment.min.js:1 Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: 
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 07/01/2019, _f: undefined, _strict: undefined, _locale: [object Object]
Error

如果加载器不存在,我不会收到错误。

【问题讨论】:

  • 为什么要混合常规的原生 JS 和 jQuery 语法?这似乎很奇怪。微调器似乎也不太可能是您的问题的根源。控制台失败时是否输出任何有用的错误消息
  • 在你的catch 中给它一个e 和console.log 的参数,这样你就可以看到实际的错误——它只是一个超时吗?
  • @mituw16 问题已编辑以包含错误。
  • @Adam 问题已编辑以包含错误
  • 我很困惑 - 注释掉微调器无法防止 500 错误。

标签: javascript jquery fetch-api


【解决方案1】:

在 promise 的 finally() 方法中停止加载器。

let loader = document.getElementById("loader");

// BEGIN LOADING
loader.style.display = 'block';

fetch(url)
  .then(resp => resp.blob())
  .then(file => {
    // HANDLE FILE
  })
  .catch(() => {
    // LOG ERROR
  })
  .finally(() => {
    // STOP LOADING
    loader.style.display = 'none';
  });

【讨论】:

  • 已编辑问题以包含错误,上面的代码无法修复它。
猜你喜欢
  • 1970-01-01
  • 2015-02-17
  • 2012-12-19
  • 2020-02-26
  • 2020-09-22
  • 2019-07-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
相关资源
最近更新 更多