FireStore文档存在检查函数始终返回undefined问题求助
问题原因分析与解决方案
你的fire_PatronExists函数始终返回undefined,核心问题出在异步操作的处理逻辑上,还有一个小的API使用错误,我来一步步拆解:
1. 为什么返回undefined?
Firestore的get()方法是异步的,它返回一个Promise对象,而你当前的函数写法里:
- 函数本身没有返回任何值(
return只写在then的回调函数内部,这个返回值不会传递到外层的fire_PatronExists函数) - 当你调用
alert(fire_PatronExists(user.uid))时,函数会立刻执行完同步代码就返回,此时异步的get()请求还没完成,所以alert拿到的是默认的undefined
另外还有个小错误:你写的doc.exists()是错的,Firestore的DocumentSnapshot对象有一个只读属性exists(不是方法),用来判断文档是否存在且有数据。
2. 修正方案(两种常用方式)
方式一:使用async/await(更直观的同步写法)
把函数改成异步函数,用await等待Promise完成,调用的时候也需要等待异步结果:
const patronsRef = db.collection("patrons"); // 标记为async函数 async function fire_PatronExists(id) { try { const docSnapshot = await patronsRef.doc(id).get(); // 直接返回exists属性 return docSnapshot.exists; } catch (error) { console.log("Error getting document:", error); // 出错时可以返回false,或者根据业务需求处理 return false; } } // 调用时需要用await,所以要放在async函数里 (async function() { const isPatronExists = await fire_PatronExists(user.uid); alert(isPatronExists); })();
方式二:直接返回Promise(传统异步写法)
让函数返回整个Promise链,调用时通过then获取结果:
const patronsRef = db.collection("patrons"); function fire_PatronExists(id) { // 直接返回Promise对象 return patronsRef.doc(id).get() .then(docSnapshot => { return docSnapshot.exists; }) .catch(error => { console.log("Error getting document:", error); return false; }); } // 调用时通过then接收结果 fire_PatronExists(user.uid).then(isExists => { alert(isExists); });
关键提醒
异步操作不会阻塞代码执行,所以永远不要像同步函数那样直接alert(fire_PatronExists(...)),必须等待Promise完成后再处理结果——要么用async/await,要么用then回调。
内容的提问来源于stack exchange,提问作者John O Sullivan
相关产品推荐
相关产品推荐

