[英]Execute 'then' in 'fetch' only if a condition is met
我有一個返回字節數組的api,使用saveAs將字節數組保存為pdf。 以下是示例代碼。 我的要求是,我可以取消兩個然后嗎? 我嘗試先放入saveascode,即使下載了pdf,也無法加載。
我有一些標頭,然后可以先檢入。 response.headers.get("status"));
僅當狀態正常時,我才需要執行第二個。 可能嗎 ? 到目前為止,即使response.ok
不是true,也將執行第二個。 有什么想法嗎 ?
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
處理程序放在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.