【问题标题】:How to chain multiple fetch calls with Promise.all? Getting response.json is not a function如何使用 Promise.all 链接多个 fetch 调用?获取 response.json 不是函数
【发布时间】: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


【解决方案1】:

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());
    }));
  }

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多