javascript - 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
^ 抽出尝试,仍然只是返回一个承诺。
解决方案
您将 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);
}
};
推荐阅读
- rust - 具有未知 len 的 Serde serialize_seq
- java - 描述 - 源服务器没有找到目标资源的当前表示或不愿意透露存在的表示
- flutter - 在 cocoapods 更新后,Flutter 项目在 iOS 上停止,安装 pod 时出错
- python - 在特定(尚不支持)语言上训练和微调 MArt
- kotlin - Kotlin 让情节:最小的例子
- mysql - 使用 Big Sur 和外部硬盘驱动器与 homebrew 一起安装时更改 mysql 数据库位置
- .net - 带有 .net 5.0 的 Docker 容器
- marklogic - 无法在 Datahub 5.2 的旧流中传递选项参数
- django - 如何从另一个 PATCH api 请求调用 PATCH api 请求?
- react-native - 对于使用“react-navigation/compat”的项目,无法将 react-navigation 从 5 迁移到 6