我试图从名为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响应
答案 0 :(得分:3)
好的,我自己想通了。这个奇怪的数据是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 */);
我不知道为什么我应该做两次“承诺解密”,但它确实有效。任何解释这一点的评论都表示赞赏。
感谢vdj4y's answer我现在理解正确。
正如我之前所写, fetch()
函数没有返回一个承诺。它返回一个Response
对象,其中包含有关请求/响应的信息(如其状态)以及ReadableStream
格式所需的数据。
json()
函数返回一个包含将ReadableStream
转换为plain js对象的结果的promise。为了操纵promise返回的数据,需要then()
函数。
此处更正的代码:
fetch(url)
.then(response => response.json())
.then(result => /* Do whatever you want with this result */)
.catch(error => /* Do something if error occurs */);
答案 1 :(得分:1)
获取返回一个Response对象,其中包含一些信息,例如请求/响应状态。服务器返回的您感兴趣的数据在Response.body上。
此数据为ReadableStream格式。响应对象具有json()函数,这将返回一个包含将readystream转换为js对象的结果的承诺。
如果服务器发送无效的json。该错误将在您运行response.json()时发生,而不是在之前。
fetch(url)
.then(response => {
console.log(response) // this contains some useful information about the reponse
return response.json(); // convert readable stream to js object, if json is invalid, you will get the error here
})
.then(result => /* Do whatever you want with this result */)
.catch(error => /* Do something if error occurs */);
答案 2 :(得分:0)
该行为是正确的,因为response.json()
实际上是一个承诺。
使用console.warn(new Promise.resolve())
批准。您将看到类似的结果。