0

哦,我又一次遇到了那些 Promise.all blues :( 我有一个函数,它从提供的 url 中创建一个 fetch 调用数组,然后我们想通过 Promise.all 检索数据并返回响应数组,或者更好的是只返回 promise调用函数。问题是这会导致控制台显示错误:

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() 并没有看到我是如何错误地使用它的。起初我以为我需要一个 Promise.all 包装器,用于responses.map((r) => r.json()) 但这也没有好处。我查看了这个链接,但我没有像他一样使用 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;
4

1 回答 1

1

当您的模板字符串fetch应该只在要获取的参数中时,它就在整个范围内:

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

然后,你有一个.then(data => {return data}),它没有做任何事情,因为returnthen回调返回,而不是函数。相反,您应该返回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);
    });
于 2020-11-27T23:56:09.777 回答