Bernard Polman
Bernard Polman

Reputation: 855

Function returned undefined, expected Promise or value - NULL value

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.

Upvotes: 0

Views: 47

Answers (1)

thezohaan
thezohaan

Reputation: 359

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();
}

Upvotes: 1

Related Questions