meerkat
meerkat

Reputation: 1122

Async function returning undefined variable

I'm trying to return a boolean from an async function, but is is coming out as undefined.

checkIfEmptyDb = async => {
    var ref = firebase.database().ref("dynamicDb");
    ref.once("value").then(snapshot => {
      const a = snapshot.exists();
      console.log(a); // false
      return a;
    });
  };

  getRandomWordFromDb = async () => {
    let moreWords = await this.checkIfEmptyDb();
    console.log("moreWords", moreWords); //UNDEFINED

My solution so far is to set the state of the react app in the checkIfEmptyDbfunction, which then can be called in getRandomWordFromDb..

Thanks in advance!

Upvotes: 0

Views: 505

Answers (1)

Inacio Schweller
Inacio Schweller

Reputation: 1986

You need to return the value of the promise:

  checkIfEmptyDb = async => {
    var ref = firebase.database().ref("dynamicDb");
    return ref.once("value").then(snapshot => {
      const a = snapshot.exists();
      console.log(a); // false
      return a;
    });
  };

Upvotes: 1

Related Questions