I have a method acting like an async method. After the request sends to the function that was called this request, I want to run something like the then method but then there is no then method for XMLHttpRequest. the caller function in below code has no then method
let result = dataService.exportfile('get', '/api/overtimeedari/exporttoexcle/', model).
then(() => {
self.loading(false);//غیرفعال کردن حالت لود شدن گرید
buttonListSearch.Excel.loading(false); //غیرفعال کردن حالت لود شدن دکمه اکسل
});
the function called
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;
}
Given the constraint of not changing exportfile
function as per comment
the case is I don't have this ability to change the
exportfile
function because it has side affects on other functions
the best way to handle this is as follows
let req = dataService.exportfile('get', '/api/overtimeedari/exporttoexcle/', model);
req.addEventListener('loadend', () => {
// do what's needed here
});
since exportfile
returns the XMLHttpRequest object, you can listen for the loadend
event and do whatever it you're doing there
Note, the loadend
event is triggered regardless of success or failure
You could do the above with the load
event if you want too - but, I'm unsure what order
x.onload=() => {};
x.addEventListener('load', () => {});
are fired ... also note, do NOT
req.onload=() => {};
since that would overwrite the onload callback inside the function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.