为什么来自JavaScript fetch API的响应对象是一个承诺? [英] Why is the response object from JavaScript fetch API a promise?

查看:130
本文介绍了为什么来自JavaScript fetch API的响应对象是一个承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When requesting from a server with JavaScript fetch API, you have to do something like

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

这里, response.json()正在解决其承诺。

Here, response.json() is resolving its promise.

问题是如果你想要捕获 404 的错误,你必须解决响应承诺,然后拒绝获取承诺,因为你只会以 catch 如果出现网络错误。所以fetch调用就像

The thing is that if you want to catch 404's errors, you have to resolve the response promise and then reject the fetch promise, because you'll only end in catch if there's been a network error. So the fetch call becomes something like

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

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

This is something much harder to read and reason about. So my question is: why is this needed? What's the point of having a promise as a response value? Are there any better ways to handle this?

推荐答案

如果您的问题是为什么 response.json ()返回一个承诺?然后@Bergi在评论中提供线索:它等待身体加载。

If your question is "why does response.json() return a promise?" then @Bergi provides the clue in comments: "it waits for the body to load".

如果你的问题是为什么不是 response.json 一个属性?,那就需要了 fetch 延迟返回其响应直到正文已加载,这可能对某些人来说是好的,但不是每个人都可以。

If your question is "why isn't response.json an attribute?", then that would have required fetch to delay returning its response until the body had loaded, which might be OK for some, but not everyone.

这个polyfill应该可以满足您的需求:

This polyfill should get you what you want:

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

反向不能进行多面填充。

The reverse cannot be polyfilled.

这篇关于为什么来自JavaScript fetch API的响应对象是一个承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆