繁体   English   中英

仅在满足条件时才在“获取”中执行“然后”

[英]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.

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