I'm developing a small card game web app. I'm using a "Rooms" system to hold each game and its players. Each room has a list of players, and I need to filter this list to only get a list of players that have a value in the Firebase Realtime DB. In this case, I'm checking their user presence in /status/{userId}
.
I thought I would be able to piece this together fairly simply, but the filtered players
array, or activePlayers
, is getting read before the filter finishes.
To demonstrate with a forEach:
function debugActivePlayers (players) {
activePlayers = []
players.forEach(player => {
firebase.ref('/status/' + player)
.once('value')
.then(snapshot => {
console.log(snapshot.val()) // 'offline' or 'online' accordingly
if (snapshot.val() === 'online') activePlayers.push(player)
return null // <-- IDE throws a fit otherwise lol
})
})
console.log(activePlayers)
}
What I expected to happen was:
offline
online
online
[userId1, userId2, userId3]
But what really happened was:
[]
offline
online
online
How do I make sure the players.forEach
(or players.filter
) runs synchronously even with async/promise logic inside (the firebase query)?