【问题标题】:Execute 'then' in 'fetch' only if a condition is met仅当满足条件时才在 'fetch' 中执行 'then'
【发布时间】: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


【解决方案1】:

如果你只想有条件地执行它,你应该把你的 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
  }
});

【讨论】:

    【解决方案2】:
    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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多