我试图做多个获取调用,以显示某些数据。然而,尝试与Promise.all()
一起工作并获得json响应并没有成功。我收到错误Unhandled Rejection (TypeError): response.json is not a function.
我怎么能改变我的方法,以便能够正确接收数据?
方法w/fetch
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()
接受承诺数组并解析为结果数组。因此,您不能在整个数组上执行.json()
。您可以单独循环每个响应对象,并在这些结果上使用另一个Promise.all()
,但是在执行Promise.all()
之前执行response.json()
要简单得多,因此Promise.all()
正在等待的承诺是.json()
承诺,因此您的结果将是一个JSON结果数组。
.map()
在这里比.forEach()
效果更好。
const getFilteredComments = (filteredSightings) => {
// loop through filtered code and apply id to each fetch call
const urlBase = 'https://ancient-mesa-60922.herokuapp.com/api/v1/reports';
return Promise.all(filteredSightings.map(sighting => {
return fetch(`${urlBase}/${sighting.id}`).then(resp => resp.json());
}));
}