【发布时间】:2021-04-29 01:01:31
【问题描述】:
除了最简单的形式之外,我对异步函数还有些陌生,所以我希望这里有人可以帮助我。
一些信息:
getCollection() 返回一个如下所示的对象数组。
{
"id": 1,
"userId": 3,
"gameId": 3498,
"review": "Testing review for game 1"
},
getGameById() 接收一个整数(游戏的 id)并从外部 API 返回该游戏对象。
gameArray 应该充满游戏对象,其外部 API 中的 ID 与 getCollection 提供的对象数组中的 ID 匹配。
const [games, setGames] = useState([])
const getGames = () => {
getCollection().then(userGames => {
let gameArray = []
for (const eachObj of userGames) {
if (eachObj.userId === currentUserId) {
getGameById(eachObj.gameId).then(game => {
gameArray.push(game)
})
}
}
Promise.all(gameArray).then(() => {
console.log(gameArray) //logs empty array, but shouldn't be empty
setGames(gameArray)
})
})
}
我以前从未使用过 Promise.all,这只是我认为可以解决我遇到的这个问题的一种方法。
【问题讨论】:
标签: javascript for-loop promise fetch