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

How to chain multiple fetch calls with Promise.all? Getting response.json is not a function

我正在尝试进行多次提取调用以显示某些数据。但是,尝试使用 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() 接受一组承诺并解析为一组结果。所以,你不能对整个数组执行 .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());
    }));
  }