You need to enable JavaScript to run this app. JS调用Firebase异步查询方法返回undefined该如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

JS调用Firebase异步查询方法返回undefined该如何解决?

修复方案

1. 改造getPatients方法,封装为Promise返回

你需要将Firebase的异步查询逻辑包裹在Promise中,查询成功时返回组装好的患者列表,查询失败时抛出错误。此外注意原代码存在一个小疏漏:患者性别字段误将整个数组赋值,没有取下标对应的值,已在下方代码中修正:

getPatients() {
  const db = firebase.database();
  const refDatabase = db.ref('patient');
  // 返回Promise对象
  return new Promise((resolve, reject) => {
    // 单次获取数据用once,避免持续监听触发重复回调
    refDatabase.once('value', elem => {
      try {
        const valuesDatabase = elem.val();
        const valuesNameArray = Object.values(valuesDatabase.name);
        const valuesAgeArray = Object.values(valuesDatabase.age);
        const valuesBirthArray = Object.values(valuesDatabase.birth);
        const valuesGenderArray = Object.values(valuesDatabase.gender);
        const valuesCountryArray = Object.values(valuesDatabase.country);
        const valuesStateArray = Object.values(valuesDatabase.state);
        const valuesCityArray = Object.values(valuesDatabase.city);
        const patients = [];
        for (let i = 0; i < valuesNameArray.length; i++) {
          patients.push({
            name: valuesNameArray[i],
            age: valuesAgeArray[i],
            birth: valuesBirthArray[i],
            gender: valuesGenderArray[i], // 修正原代码未取下标的问题
            country: valuesCountryArray[i],
            state: valuesStateArray[i],
            city: valuesCityArray[i]
          });
        }
        // 查询成功返回结果
        resolve(patients);
      } catch (err) {
        // 数据组装出错时返回错误
        reject(err);
      }
    }, err => {
      // 查询请求出错时返回错误
      reject(err);
    })
  })
};

2. 修改调用逻辑

因为方法返回的是Promise,你可以通过两种方式拿到最终结果:

方式1:使用.then链式调用

const newPatient = new PatientService();
newPatient.getPatients()
  .then(patients => {
    console.log(patients);
    // 后续处理患者列表的逻辑写在这里
  })
  .catch(err => {
    console.error('获取患者列表失败', err);
  })

方式2:使用async/await语法(更简洁)

const newPatient = new PatientService();
// 需要包裹在async函数内使用
async function fetchPatients() {
  try {
    const patients = await newPatient.getPatients();
    console.log(patients);
    // 后续处理患者列表的逻辑写在这里
  } catch (err) {
    console.error('获取患者列表失败', err);
  }
}
// 执行函数
fetchPatients();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:24:10