【发布时间】:2020-01-10 12:40:31
【问题描述】:
我有一个返回字节数组的 api,使用 saveAs 将字节数组保存为 pdf。以下是示例代码。我的要求是,我可以取消两个 then 吗?然后我尝试先将 saveascode 放入,即使下载了 pdf,也无法加载。
我有一些标题,然后我可以先签入。
response.headers.get("status"));
只有当状态正常时,我才需要执行第二个。
可能吗 ?
截至目前,即使response.ok 不为真,第二个 then 也会被执行。有什么想法吗?
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);
}
【问题讨论】:
-
你需要两个,因为
response.blob()也会返回一个承诺。 -
你可以将
fetch包裹到你自己的层中 -
好的,但是如果状态不正常,那么可以更改代码以便不执行第二个 then 吗?
-
你可以在状态不是“ok”的情况下抛出,然后你可以在第二个之后添加catch
-
这里是代码 fetch(param) .then(function(response) { if (response.headers.get("status")) != 'ok') { throw new Error('not OK') } 返回 response.blob(); }) .then(function(response) { if (response == undefined) { //handle } else { const file = new Blob([response], { type: 'application/pdf', }); saveAs(file,文件名); }) .catch(e) {}
标签: javascript reactjs promise fetch