简体   繁体   中英

Execute 'then' in 'fetch' only if a condition is met

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);
      }
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:

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
  }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM