Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

javascript - Firebase Cloud Function "ForEach" child of a Snapshot not called onCreate

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...