Reputation: 2069
I have an api returning bytearray, using saveAs for saving the bytearray to 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.
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. 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);
}
Upvotes: 1
Views: 1125
Reputation: 664346
Then you should put your then
handler inside that if
block if you only want to execute it conditionally:
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
}
});
Upvotes: 1
Reputation: 871
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
});
Upvotes: 1