Warm tip: This article is reproduced from serverfault.com, please click

javascript-在Promise.all上获取.json不是函数w / fetch

(javascript - Getting .json is not a function on Promise.all w/fetch)

发布于 2020-11-27 23:38:07

再次,我有那些Promise.all blues:((我有一个函数,该函数从提供的url进行获取调用的数组,然后我们要通过Promise.all检索数据,并返回响应数组或更好的方法,只是返回promise调用函数。问题是这会导致出现错误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(),但看不到我的使用方式有误。起初我以为我需要一个Promise.all包装器来响应.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;
Questioner
Alan
Viewed
11
Aplet123 2020-11-28 07:56:09

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