kevin
kevin

Reputation: 3488

firestore function only returns a promise

I've been trying to solve this for ages now and I'm not closer than I was at the start. I starting to think I'm looking in the wrong place, but I have no idea.

simple firebase function:

export const fsFetchLesson = async (language: string, id: string) => {
  const docRef = firebaseFirestore
    .collection(`lessons/source_language/${language}`)
    .doc(id)

  try {
    await docRef.get().then((doc) => {
      if (doc.exists) {
        // console.log('doc', doc.data());   //  <-- logs the correct doc
        return doc.data();                   //  <-- returns a promise
      }
      console.log('No such document found');
    });
  } catch (error) {
    console.log('Error finding collection', error);
  }
};

I need fsFetchLesson to return the value of doc.data(), yet the output of this function is a pending promise. Same thing happens if I copy paste the exact then() solution from the firebase documentation. Still just returns a pending promise.


const fsFetchLesson = async (language: string, id: string) => {
  const docRef = firebaseFirestore
    .collection(`lessons/source_language/${language}`)
    .doc(id);

  try {
    await docRef.get().then((doc) => {
      if (doc.exists) {
        // console.log('doc', doc.data());
        return doc.data();
      }
      console.log('No such document found');
    });
  } catch (error) {
    console.log('Error finding collection', error);
  }
};

// ! HERE
const a = async () => {
  const data = await fsFetchLesson('english', 'zlnWzwJ6rhZeKOZXdqIS');
  return data;
};

const b = a();
console.log(b);
// returns promise pending

^ drawn out attempt, still just returns a promise.

Upvotes: 0

Views: 45

Answers (1)

Michael Bleigh
Michael Bleigh

Reputation: 26313

You are mixing promises and async/await which often causes confusion. For one, an async function will always return a Promise, no matter what. That's how async functions work. In this case, you end up executing a separate promise chain in the middle of the function without waiting for a result. Try something like this instead:

export const fsFetchLesson = async (language: string, id: string) => {
  const docRef = firebaseFirestore
    .collection(`lessons/source_language/${language}`)
    .doc(id);

  try {
    const doc = await docRef.get()
    if (doc.exists) {
      // console.log('doc', doc.data());   //  <-- logs the correct doc
      return doc.data();                   //  <-- returns the data
    }
    console.log('No such document found');
  } catch (error) {
    console.log('Error finding collection', error);
  }
};

Upvotes: 2

Related Questions