javascript - React Native fetch() 返回奇怪的 json 响应项

标签 javascript json fetch react-native

我正在尝试从名为 OpenWeatherMap 的服务获取 JSON 格式的数据,因此在我的 componentWillMount 方法中,我调用 fetch() 以通过 url 返回数据。我现在的代码是:

this.weather = fetch(url).then(response => response.json()).then(responseJson => responseJson);

它有效,但在 JSON 响应中返回奇数数据,我现在的 JSON 响应是:

{"_40":0,"_65":1,"_55":{here_the_correct_response}}

但我希望我的响应没有这些奇怪的下划线索引,只是纯 JSON 响应

最佳答案

好吧,我自己想通了。这个奇怪的数据就是所谓的 fetch() 返回的 promise 。为了摆脱这个我这样做了:

fetch(url)
    .then(response => response.json().then(data => data))
    .then(result => /* Do whatever you want with this result */)
    .catch(error => /* Do something if error occurs */);

我不知道为什么我应该做两次“ promise 解密”,但它有效。任何对此进行解释的评论都将受到赞赏。

更新

感谢vdj4y's answer我现在理解正确了。

fetch() 函数没有返回 promise ,正如我之前写的那样。它返回一个 Response 对象,其中包含有关请求/响应的信息(如其状态)和我们需要的 ReadableStream 格式的数据。

json() 函数反过来返回一个 promise ,其中包含将 ReadableStream 转换为纯 js 对象的结果。为了操作 promise 返回的数据,需要 then() 函数。

此处更正代码:

fetch(url)
    .then(response => response.json())
    .then(result => /* Do whatever you want with this result */)
    .catch(error => /* Do something if error occurs */);

关于javascript - React Native fetch() 返回奇怪的 json 响应项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46538248/

相关文章:

node.js - 多少个提取请求过多?

javascript - 如何单击没有 onclick 事件的表单提交输入,但在页面中单击时会发生某些情况如何单击它?在 C# 中?

php - 从 kml 文件计算地面覆盖 Angular 的纬度/经度

java - Volley Post 请求在 onResponse 内未返回任何响应

json - 为什么 Mongoose 用 "[object Object]"替换子文档?

javascript - 以 html 形式获取帖子响应,但也包含状态

javascript - kue - 处理不同文件中的作业

基于 Javascript 的交互式 map 应用程序

java - 将 JSONArray 拆分为更小的 JSONArray

php - 选择获取数组中的不同项目