我正在尝试实现一个函数,根据给定的 ID 检查我的 FireStore 数据库中是否存在文档。问题是我的 fire_PatronExists
函数总是返回 undefined
。
const patronsRef = db.collection("patrons");
alert(fire_PatronExists(user.uid));
function fire_PatronExists(id) {
patronsRef.doc(id).get().then(function(doc) {
// return doc.exists();
if (doc){return true}else {return false}
}).catch(function(error) {
console.log("Error getting document:", error);
});
}
最佳答案
您的函数返回未定义的事实是完全正常的:get()
是一个异步方法,因此您放入 then
内的返回值不会在 fire_PatronExists
内执行;它会稍后执行。有一个great SO article这解释了同步执行和异步执行之间的区别。
根据您使用的 JavaScript 版本,有不同的解决方案。一个肯定有效的方法是将回调函数传递给 fire_PatronExists
并将结果传递给该函数。
这看起来像这样(未经测试):
const patronsRef = db.collection("patrons");
fire_PatronExists(user.uid, function(exists) {
alert(exists);
});
// Remember though, if you put code here, it will be executed in parallel
// with the code you put inside your callback.
function fire_PatronExists(id, callback) {
patronsRef.doc(id).get().then(function(doc) {
}).catch(function(error) {
console.log("Error getting document:", error);
});
}
不过,使用回调可能会变得非常困惑。如果您使用的是最新版本的 JavaScript,您可能需要 read about async
和await
关键字,它们可以大大提高代码的可读性。
关于javascript - 调用 FireStore 的函数始终返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49712000/