哦,我又一次遇到了那些 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;