【发布时间】:2021-03-02 08:01:50
【问题描述】:
我正在尝试进行多次 fetch 调用以显示某些数据。但是,尝试使用 Promise.all() 并获得 json 响应并没有成功。我收到错误 Unhandled Rejection (TypeError): response.json is not a function. 我如何更改我的方法才能正确接收数据?
获取方法
const getFilteredComments = (filteredSightings) => {
let filteredComments = [];
// loop through filtered code and apply id to each fetch call
filteredSightings.forEach(sighting => {
filteredComments.push(fetch(`https://ancient-mesa-60922.herokuapp.com/api/v1/reports/${sighting.id}`))
})
Promise.all(filteredComments)
.then(response => response.json())
.then(data => console.log(data))
}
如果我只是 console.log() 响应
0: Response
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "https://ancient-mesa-60922.herokuapp.com/api/v1/reports/14"
__proto__: Response
【问题讨论】:
-
Promise.all 解析为一个 array,它没有 JSON 方法,但包含有响应的响应。
.push(fetch(...).then(response => response.json()))可能更容易。
标签: javascript reactjs promise es6-promise