[英]Promise.all returns [[PromiseValue]] but I need array of all returned values
我試圖返回json對象的數組,但下面的代碼返回[[PromiseValue]],數據肯定在那里。
“功能結果”
注意:如果我在getEndResults
函數中調用.then(data => console.log(data))
,但是我無法在那里getEndResults
,因為它會拋出錯誤
警告:setState(...):只能更新已安裝或安裝的組件。 這通常意味着您在已卸載的組件上調用了setState()。 這是一個無操作。
getUserCredits = async (userId, creditId) => {
return await fetch(
`${someLink}/userId/${userId}/credit/${creditId}`,
{
method: "GET",
}
)
}
getEndResult = async () => {
const userId = await this.getUserId(userId);
const userData = await this.getUserData(userId);
const checkData = await Promise.all(userData.checks.map(check => {
return check.checkIds.map((checkIds) => {
return this.getUserCredits(userId ,checkIds)
.then(res => res.json())
.then(data => console.log(data))
// Can't setState here
// .then(data => this.setState({ results: data }))
})
}))
console.log(checkData);
}
你正在創建一個二維的promises數組,然后將它傳遞給Promise.all。 Promise.all只知道如何使用單維數組,所以它看到的是一個不承諾的數組。 對於非承諾,promises.all只是立即解析它給出的值。
在將其發送到Promise.all之前,您需要將二維數組展平。 如果你有一個array.prototype.flatmap的polyfill (很快就會添加到javascript中,但還沒有),可以這樣做:
const checkData = await Promise.all(userData.checks.flatMap(check => {
return check.checkIds.map((checkIds) => {
return this.getUserCredits(userId, checkIds)
.then(res => res.json());
});
如果您無法使用該功能,那么您可以編寫自己的函數來展平2d數組,如下所示:
function flatten(arr) {
const result = [];
arr.forEach(val => {
if (Array.isArray(val)) {
result.push(...val);
} else {
result.push(val);
}
});
return result;
}
// used like:
const promises = flatten(userData.checks.map(check => {
// ... etc
}));
const checkData = await Promise.all(promises);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.