firestore函数只返回一个promise



我已经尝试解决这个问题很长时间了,现在我已经不比一开始更接近了。我开始觉得我找错地方了,但我不知道。

简单的火球功能:

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()的值,但是这个函数的输出是一个挂起的promise。如果我从firebase文档中复制粘贴确切的then()解决方案,也会发生同样的情况。仍然只是返回一个待定的承诺。


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

^旷日持久的尝试,仍然只是回报一个承诺。

您混合了promise和async/await,这通常会导致混乱。例如,async函数将始终返回Promise,无论如何。这就是async的工作原理。在这种情况下,您最终会在函数中间执行一个单独的承诺链,而无需等待结果。试试这样的东西:

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

最新更新