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

查看:13
本文介绍了为什么来自 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() 返回一个 promise?"然后@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));

反向不能被填充.

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

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