再次,我有那些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;
fetch
当模板字符串仅应包含在访存参数中时,它是整个字符串:
params.forEach((param) => {
queryURLs.push(fetch(`${url}${new URLSearchParams(param)}`, {
method: "get",
headers: {
Authorization:
"Basic *****==",
}
}));
});
然后,你有一个.then(data => {return data})
,它不会执行任何操作,因为return
从then
回调而不是函数返回。你应该返回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);
});
谢谢!我如何使用返回的数据。我以为this.qbLeaders = LeagueLeadersResponseArray [0] .cumulativeplayerstats.playerstatsentry; 可以让我访问API的第一个响应。但是我知道它是不确定的。
您应该
console.log(leagueLeadersResponseArray)
确保数据符合预期。现在我很困惑。我以为一旦Promise.all解决了,然后LeagueLeadersResponseArray就会将我的三个仓库作为每个文档的数组。相反,我有这个:这是返回的LeagueLeaders数组[object Promise],[object Promise],[object Promise]。有什么建议么。
哦,您可能会想要更改
queryURLs.push(fetch(...))
为queryURLs.push(fetch(...).then((res) => res.json())
,它将起作用。查看更新的代码。现在,我们回到了检索数据时遇到的问题。TypeError:r.json不是函数错误。???