Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Promise.all链接多个fetch调用?获取response.json不是一个函数_Javascript_Reactjs_Promise_Es6 Promise - Fatal编程技术网

Javascript 如何使用Promise.all链接多个fetch调用?获取response.json不是一个函数

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(视

为了显示某些数据,我正在尝试执行多个fetch调用。但是,尝试使用
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());
    }));
  }