首页 文章

为什么来自JavaScript fetch API的响应对象是一个承诺?

提问于
浏览
26

从具有JavaScript fetch API的服务器请求时,您必须执行类似的操作

fetch(API)
  .then(response => response.json())
  .catch(err => console.log(err))

在这里, response.json() 正在履行其承诺 .

问题是,如果你想要捕获 404 's errors, you have to resolve the response promise and then reject the fetch promise, because you' ll只在 catch 结束,如果出现网络错误 . 所以fetch调用就像是

fetch(API)
  .then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
  .catch(err => console.log(err))

这是一个更难阅读和推理的东西 . 所以我的问题是:为什么需要这个?将承诺作为回应 Value 有什么意义?有没有更好的方法来处理这个?

1 回答

  • 20

    如果你的问题是“为什么 response.json() 会返回一个承诺?" then @Bergi provides the clue in comments: "它会等待正文加载” .

    如果你的问题是“为什么不是 response.json 属性?”那么那将需要 fetch 来延迟返回它的响应直到主体加载,这对某些人来说可能没问题,但不是每个人都可以 .

    这个polyfill应该得到你想要的:

    var fetchOk = api => fetch(api)
      .then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));
    

    然后你可以这样做:

    fetchOk(API)
      .then(response => response.json())
      .catch(err => console.log(err));
    

    反向不能是polyfilled .

相关问题