Ily*_*tov 4 javascript json fetch react-native-android
我正在尝试从名为 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()。为了摆脱这种情况,我这样做了:
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 */);
Run Code Online (Sandbox Code Playgroud)
我不知道为什么我应该做两次“承诺解密”,但它有效。任何解释这一点的评论表示赞赏。
感谢vdj4y 的回答,我现在正确理解了。
fetch()函数没有返回承诺,就像我之前写的那样。它返回一个Response对象,其中包含有关请求/响应的信息(如其状态)和我们需要的ReadableStream格式数据。
json()反过来,函数返回一个包含转换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 */);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2306 次 |
| 最近记录: |