为什么来自 JavaScript fetch API 的响应对象是一个承诺?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32721850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is the response object from JavaScript fetch API a promise?
提问by amb
When requesting from a server with JavaScript fetch API, you have to do something like
当使用 JavaScript fetch API 从服务器请求时,您必须执行类似的操作
fetch(API)
.then(response => response.json())
.catch(err => console.log(err))
Here, response.json()
is resolving its promise.
在这里,response.json()
正在解决它的承诺。
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
问题是如果你想捕获404
错误,你必须解决响应承诺,然后拒绝获取承诺,因为只有在catch
出现网络错误时才会结束。所以 fetch 调用变得像
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?
这是更难阅读和推理的东西。所以我的问题是:为什么需要这样做?将承诺作为响应值有什么意义?有没有更好的方法来处理这个问题?
采纳答案by jib
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()
返回承诺?” 然后@Bergi 在评论中提供了线索:“它等待身体加载”。
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.
如果您的问题是“为什么不是response.json
属性?”,那么这将需要fetch
延迟返回其响应,直到主体加载完毕,这对某些人来说可能没问题,但不是所有人。
This polyfill should get you what you want:
这个 polyfill 应该可以满足你的需求:
var fetchOk = api => fetch(api)
.then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));
then you can do:
那么你可以这样做:
fetchOk(API)
.then(response => response.json())
.catch(err => console.log(err));
The reverse cannot be polyfilled.
反之不能为 polyfill。