0

I want to access a document collection and get one random document that starts with a random chosen letter:

function generateWord() {

var wordsDb = database.ref('words');
var possibleChars = "abcdefghijklmnopqrstuvwyz";
var randomLetter = possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));

wordsDb.startAt(randomLetter).limitToFirst(1).once('value', (snapshot) => {
    console.log(snapshot.val());
    return snapshot.val();
  });
}

I use the function inside an exported function that is triggered when a document in another collection is created:

 var firstWord = generateWord();

            var game = {
                gameInfo: {
                    gameId: gameId,
                    playersIds: [context.params.playerId, secondPlayer.key],
                    wordSolution: firstWord,
                    round: 0
                },
                scores: {
                    [firstPlayerScore]: 0,
                    [secondPlayerScore]: 0
                },
            }

This is what the collection looks like:

enter image description here

I get the following warning in console log:

Function returned undefined, expected Promise or value

And also, console.log(snapshot.val()); shows that snapshot.val() is null.

Is my syntax wrong? I just want to get the value of the document.

Bernard Polman
  • 795
  • 2
  • 14
  • 31
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Feb 12 '23 at 16:52
  • Your function `generateWord` doesn't return anything. `return snapshot.val()` returns only from the callback ... – derpirscher Feb 12 '23 at 16:54

1 Answers1

1

Your code is executed before the data is received. Try to use async/await to wait for the data to return from firebase.

async function generateWord() {

var wordsDb = database.ref('words');
var possibleChars = "abcdefghijklmnopqrstuvwyz";
var randomLetter = possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));

var word = await wordsDb.startAt(randomLetter).limitToFirst(1).once('value') 
return word.val();
}
thezohaan
  • 324
  • 1
  • 10