Javascript 如何使用Promise.all链接多个fetch调用?获取response.json不是一个函数
为了显示某些数据,我正在尝试执行多个fetch调用。但是,尝试使用Javascript 如何使用Promise.all链接多个fetch调用?获取response.json不是一个函数,javascript,reactjs,promise,es6-promise,Javascript,Reactjs,Promise,Es6 Promise,为了显示某些数据,我正在尝试执行多个fetch调用。但是,尝试使用Promise.all()并获得json响应并没有成功。我收到了错误未处理的拒绝(TypeError):response.json不是函数。如何更改我的方法以正确接收数据 方法w/fetch const getFilteredComments=(FilteredLightings)=>{ 让filteredComments=[]; //循环过滤代码并将id应用于每个提取调用 FilteredLightings.forEach(视
Promise.all()
并获得json响应并没有成功。我收到了错误未处理的拒绝(TypeError):response.json不是函数。
如何更改我的方法以正确接收数据
方法w/fetch
const getFilteredComments=(FilteredLightings)=>{
让filteredComments=[];
//循环过滤代码并将id应用于每个提取调用
FilteredLightings.forEach(视野=>{
filteredComments.push(获取)(`https://ancient-mesa-60922.herokuapp.com/api/v1/reports/${sighting.id}`)
})
承诺。所有(过滤建议)
.then(response=>response.json())
.then(数据=>console.log(数据))
}
Promise.all()
接受承诺数组并解析为结果数组。因此,不能对整个数组执行.json()
。您可以分别在每个响应对象上循环,并在这些结果上使用另一个Promise.all()
,但是在执行Promise.all()
之前只执行response.json()
要简单得多,所以Promise.all()
等待的承诺就是.json()
承诺,因此您的结果将是一个JSON结果数组
而且.map()
在这里比.forEach()
更有效
all解析为一个数组,该数组没有JSON方法,但包含有JSON方法的响应。推送(fetch(…)。然后(response=>response.json())可能更容易。
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());
}));
}