获取 .json 不是 Promise.all w/fetch 上的函数

Getting .json is not a function on Promise.all w/fetch

哦,我又一次遇到了那些 Promise.all 忧郁:( 我有一个函数,它从提供的 url 中创建一个获取调用的数组,然后我们想通过 Promise.all 和 return 响应数组或更好只是 return 调用函数的承诺。问题是这导致错误 w/console 显示:

There was problem retrieving data. TypeError: r.json is not a function

函数的代码是:

 const getLeagueLeaders = (url, params) => {
  // First let's create the array of url's
  let queryURLs = [];

  params.forEach((param) => {
    queryURLs.push(
      fetch(`${url}${new URLSearchParams(param)}`, {
        method: "get",
        headers: {
          Authorization:
            "Basic ==",
        },
      }).then((res) => res.json())
    );
  });

  return (
    Promise.all(queryURLs)
      // map array of responses into an array of response.json() to read their content
      .then((responses) => responses.map((r) => r.json()))
      .catch((err) => {
        console.error("There was problem retrieving data.", err);
      })
  );
};
    
    module.exports = getLeagueLeaders;

而在 Vue 组件中

 mounted: async function () {
        const leagueLeadersResponseArray = await getLeagueLeaders(
          this.fetchBaseUrl,
          this.params
        );
this.qbLeaders =
      leagueLeadersResponseArray[0].cumulativeplayerstats.playerstatsentry;

显然 leagueLeadersResponseArray 未定义。我研究了 .json() 并且看不出我是如何错误地使用它的。起初我以为我需要一个 responses.map((r) => r.json()) 的 Promise.all 包装器,但这也没有用。我看了这个 但我没有像他那样使用 fetch。非常感谢任何指导....

为其他人更新的工作代码:

// ---------- src/js/modules/ ------------------ //

/* jshint ignore:start */
// Make function to retrieve League Leaders in a Category

const getLeagueLeaders = (url, params) => {
  // First let's create the array of url's
  let queryURLs = [];

  params.forEach((param) => {
    queryURLs.push(
      fetch(`${url}${new URLSearchParams(param)}`, {
        method: "get",
        headers: {
          Authorization:
            "Basic ==",
        },
      }).then((res) => res.json())
    );
  });

  return Promise.all(queryURLs).catch((err) => {
    console.error("There was problem retrieving data.", err);
  });
};

module.exports = getLeagueLeaders;

你的模板字符串在整个 fetch 周围,而它应该只在要获取的参数中:

  params.forEach((param) => {
    queryURLs.push(fetch(`${url}${new URLSearchParams(param)}`, {
      method: "get",
      headers: {
        Authorization:
          "Basic *****==",
      }
    }));
  });

然后,你有一个 .then(data => {return data}),自从 then 回调的 return return 之后,它什么都不做, 函数。您应该 return Promise.all 给您的承诺:

  return Promise.all(queryURLs)
    // map array of responses into an array of response.json() to read their content
    .then((responses) => responses.map((r) => r.json())) // Get error There was problem retrieving data. TypeError: r.json is not a function
    .catch((err) => {
      console.error("There was problem retrieving data.", err);
    });