[英]Execute 'then' in 'fetch' only if a condition is met
I have an api returning bytearray, using saveAs for saving the bytearray to pdf. 我有一个返回字节数组的api,使用saveAs将字节数组保存为pdf。 The following is sample code. 以下是示例代码。 My requirement is, can I do away with two thens ? 我的要求是,我可以取消两个然后吗? I tried putting the saveascode in first then, even though a pdf is downloaded, it is not able to load. 我尝试先放入saveascode,即使下载了pdf,也无法加载。
I have some headers, which I can check in first then. 我有一些标头,然后可以先检入。 response.headers.get("status"));
Only if the status is ok, I need to execute the second then. 仅当状态正常时,我才需要执行第二个。 is it possible ? 可能吗 ? As of now, even if response.ok
is not true, the second then is executed. 到目前为止,即使response.ok
不是true,也将执行第二个。 Any thoughts ? 有什么想法吗 ?
fetch(param).then(function(response) {
if (response.headers.get("status")) == 'ok') {
return response.blob();
}
}).then(function(response) {
if (response == undefined) {
//handle
} else {
const file = new Blob([response], {
type: 'application/pdf',
});
saveAs(file, fileName);
}
fetch(param).then(function (response) {
if (response.headers.get("status") == 'ok') {
return response.blob();
}
else { throw new Error("Status is not ok"); }
}).then(function (response) {
if (response == undefined) {
//handle
} else {
const file = new Blob([response], {
type: 'application/pdf',
});
saveAs(file, fileName);
}
}, function (statusNotOKError) {
//do handling if needed
});
Then you should put your then
handler inside that if
block if you only want to execute it conditionally: 如果只想有条件地执行,则应将then
处理程序放在if
块中:
fetch(param).then(function(response) {
if (response.headers.get("status")) == 'ok') {
return response.blob().then(function(response) {
const file = new Blob([response], {
type: 'application/pdf',
});
saveAs(file, fileName);
}
} else {
// handle
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.