【问题标题】:Running then method after XMLHttpRequest done在 XMLHttpRequest 完成后运行 then 方法
【发布时间】:2021-10-02 02:09:16
【问题描述】:

我有一个类似于异步方法的方法。在请求发送到调用这个请求的函数之后,我想运行类似 then 方法的东西,但是没有用于 XMLHttpRequest 的 then 方法。 下面代码中的调用函数没有then方法

      let result = dataService.exportfile('get', '/api/overtimeedari/exporttoexcle/', model).
                then(() => {
                        self.loading(false);//غیرفعال کردن حالت لود  شدن گرید
                        buttonListSearch.Excel.loading(false); //غیرفعال کردن حالت لود شدن دکمه اکسل
                    });

调用的函数

        function exportfile(mehtodtype, url, model) {
            debugger;
            var qs = "?";
            model.map((item) => {
                qs = `${qs}${item.name}=${item.value}&`;
            });

            var request = new XMLHttpRequest();
            request.open(mehtodtype, url + qs, true);
            request.setRequestHeader('Authorization', "Bearer " + window.localStorage.getItem('token'));
            request.responseType = 'blob';
            request.onload = function (e) {
                if (this.status === 200) {
                    var blob = this.response;
                    if (window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveBlob(blob, fileName);
                    }
                    else {
                        var downloadLink = window.document.createElement('a');
                        var contentTypeHeader = request.getResponseHeader("Content-Type");
                        downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader }));
                        downloadLink.download = "Export.xls";
                        document.body.appendChild(downloadLink);
                        downloadLink.click();
                        document.body.removeChild(downloadLink);
                    }
                }
            };
            request.send();
            return request;
        }

【问题讨论】:

  • XHMHttpRequest 没有.then 属性——你可能在想fetch 吗?或其他返回承诺的东西?承诺是具有.then 方法的东西 - 如果您绝对必须使用XMLHttpRequest,您当然可以将function exportfile 中的代码包装在Promise 中
  • @Bravo 我需要在 XMLHttpRequest 完成后运行回调函数之类的东西。
  • 当然,然后这样做 - 向 exportfile 提供一个回调函数并在需要时调用它 - 这也有效
  • @Bravo 情况是我没有这种能力来改变`exportfile`功能,因为它对其他功能有副作用

标签: javascript c# xmlhttprequest


【解决方案1】:

鉴于不根据评论更改exportfile函数的约束

情况是我没有更改exportfile 函数的能力,因为它对其他函数有副作用

最好的处理方法如下

let req = dataService.exportfile('get', '/api/overtimeedari/exporttoexcle/', model);
req.addEventListener('loadend', () => {
  // do what's needed here
});

由于 exportfile 返回 XMLHttpRequest 对象,您可以侦听 loadend 事件并执行您正在执行的操作

注意,无论成功还是失败都会触发loadend事件

如果您愿意,也可以使用 load 事件执行上述操作 - 但是,我不确定什么顺序

x.onload=() => {};
x.addEventListener('load', () => {});

被解雇...另请注意,不要

req.onload=() => {};

因为这会覆盖函数内部的 onload 回调

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多