I am making a multiplayer game with cloud functions.
HOW IT WORKS:
Every time a user joins a matchmaking room, the client creates a matchmaking tree with that player's id. The server reads this matchmaking tree and iterates through each player in the snapshot. It checks which player has a "placeholder" value of gameId and creates a second player.
THE PROBLEM is forEach of snapshot is only called the first two or three times when players join. When another player joins the room later, secondPlater returns null, meaning it did not iterate through each player.
Here is the code with logs:
exports.matchmaker = functions.database.ref('matchmaking/{playerId}')
.onCreate((snap, context) => {
console.log("joined queue");
var gameId = generateGameId();
database.ref('matchmaking').once('value').then(snapshot => {
var secondPlayer = null;
// Search for a player who is not yet matched in the queue
snapshot.forEach(child => { // error: not reading the players
var playerId = child.key
var gameId = child.val().gameId
console.log(playerId);
console.log(gameId);
// Check for an open player and is not the player who just joined
if (gameId === "placeholder" && playerId !== context.params.playerId) {
secondPlayer = child;
}
});
console.log("Second player");
console.log(secondPlayer);
if (secondPlayer === null) return null;
// DO OTHER STUFF and access secondplayer's values
I would really really appreciate any help.
question from:
https://stackoverflow.com/questions/65897539/firebase-cloud-function-foreach-child-of-a-snapshot-not-called-oncreate 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…