You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:49:13