首页 > 解决方案 > firestore 函数只返回一个承诺

问题描述

我已经尝试解决这个问题很久了,但我并没有比一开始更接近。我开始认为我找错地方了,但我不知道。

简单的火力基地功能:

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

我需要fsFetchLesson返回 的值doc.data(),但这个函数的输出是一个未决的承诺。then()如果我从 firebase 文档中复制粘贴确切的解决方案,也会发生同样的事情。仍然只是返回一个未决的承诺。


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

^ 抽出尝试,仍然只是返回一个承诺。

标签: javascriptreactjsfirebase

解决方案


您将 promise 和 async/await 混合在一起,这通常会导致混淆。一方面,一个async函数总是会返回一个 Promise,不管是什么。这就是async函数的工作方式。在这种情况下,您最终会在函数中间执行一个单独的 Promise 链,而无需等待结果。尝试这样的事情:

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

推荐阅读