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

从Firestore获取文档时导出函数返回Undefined问题排查

Firestore获取用户信息返回undefined的问题解决

问题现象

  • 调用getUserInfo函数时,内部getDoc能成功获取Firestore文档数据,但函数返回值始终为undefined
  • 执行userinfo.data()时抛出错误:Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
  • 内部打印的文档数据正常:{area: '', id: 'jX3J5XjwDphlE1rQRxlxOHyDqMI2', email: 'userExaple@gmail.com', phone: '6181690397', userName: 'Edmundo Gurrola', …}

错误原因

getUserInfo函数未返回Promise,内部onAuthStateChanged是异步监听逻辑,getDoc的then回调返回值无法传递到函数外部,导致函数执行完毕直接返回undefined,await无法等待异步操作完成。

修正方案

将getUserInfo包装为返回Promise的函数,在用户认证状态可用且成功获取文档后,通过resolve返回结果;若用户未登录或获取失败,通过reject抛出错误。

修正后的代码

Firebase模块代码

export const getUserInfo = (collection) => {
  // 用Promise包裹异步逻辑
  return new Promise((resolve, reject) => {
    onAuthStateChanged(auth, async (user) => {
      if (user) {
        try {
          const docSnapshot = await getDoc(doc(db, collection, user.uid));
          if (docSnapshot.exists()) {
            console.log(docSnapshot.data());
            resolve(docSnapshot);
          } else {
            reject(new Error("用户文档不存在"));
          }
        } catch (error) {
          reject(error);
        }
      } else {
        reject(new Error("用户未登录"));
      }
    });
  });
};

Home.js代码

window.addEventListener('DOMContentLoaded', async() => {
  UserStatus()
  
  try {
    const userinfo = await getUserInfo('UniversityStaff');
    const userProfile = userinfo.data();
    let html ='';
    html+=`
    <h5><b>Usuario:</b>${userProfile.userName}</h5>
    <h5><b>Correo institucional:</b>${userProfile.email}</h5>
    <h5><b>Telefono:</b>${userProfile.phone}</h5>
    <h5><b>Departamento:</b>${userProfile.area}</h5>
    <h5><b>Puesto:</b>${userProfile.jobTitle}</h5>
    <h5><b>Horario:</b>${userProfile.workingHours}</h5>`

    userInfo.innerHTML = html;
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
})

说明

  • 用Promise包裹异步流程,确保await能正确等待结果返回
  • 添加try/catch处理异步操作中的错误,避免未捕获异常
  • 增加文档存在性判断,处理用户文档不存在的边界情况

内容的提问来源于stack exchange,提问作者Chris_Tophy GC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:12:10