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

如何等待Firebase数据拉取完成后再调用getDistance函数

问题原因

你遇到的是典型的异步调用时序问题:

  • getLngLat 内部的Firebase数据请求是异步操作,不会阻塞后续代码执行
  • 你虽然给getLngLat加了async标记,但既没有返回内部的Promise,也没有在componentDidMount中等待异步操作完成,就直接调用了getDistance,导致此时经纬度数据还没被赋值。同时原有getLngLat代码里还有一处多余的右括号语法错误。
修复方案(两种可选)

方案1:async/await 写法(推荐,代码可读性更高)

// 改造getLngLat,用await处理异步请求
getLngLat = async () => {
  const driverId = firebase.auth().currentUser.uid;
  const snapshot = await firebase
    .database()
    .ref("Ride_Request/" + driverId)
    .once("value");

  if (snapshot.exists()) {
    DriverHomeContents.RiderPickUpLatitude = snapshot.child("pickupLatitude").val();
    DriverHomeContents.RiderPickUpLongitude = snapshot.child("pickupLongitude").val();
    DriverHomeContents.RiderDropUpLatitude = snapshot.child("dropOffLatitude").val();
    DriverHomeContents.RiderDropUpLongitude = snapshot.child("dropOffLongitude").val();
    // 返回成功标识,方便后续判断
    return true;
  } else {
    this.toast.show("No ride requests", 500);
    return false;
  }
}

// 改造componentDidMount为async函数,等待getLngLat执行完成
componentDidMount = async () => {
  const hasData = await this.getLngLat();
  // 只有拿到数据后才调用距离计算函数
  if (hasData) {
    this.getDistance(
      DriverHomeContents.RiderPickUpLatitude,
      DriverHomeContents.RiderPickUpLongitude,
      DriverHomeContents.RiderDropUpLatitude,
      DriverHomeContents.RiderDropUpLongitude
    );
  }
}

方案2:Promise .then 链式调用写法

如果你不想修改componentDidMount的async标记,也可以直接在getLngLat返回Promise后链式调用getDistance:

// 改造getLngLat,返回内部的Promise
getLngLat = () => {
  const driverId = firebase.auth().currentUser.uid;
  // 直接返回Firebase的Promise
  return firebase
    .database()
    .ref("Ride_Request/" + driverId)
    .once("value")
    .then((snapshot) => {
      if (snapshot.exists()) {
        DriverHomeContents.RiderPickUpLatitude = snapshot.child("pickupLatitude").val();
        DriverHomeContents.RiderPickUpLongitude = snapshot.child("pickupLongitude").val();
        DriverHomeContents.RiderDropUpLatitude = snapshot.child("dropOffLatitude").val();
        DriverHomeContents.RiderDropUpLongitude = snapshot.child("dropOffLongitude").val();
        return true;
      } else {
        this.toast.show("No ride requests", 500);
        return false;
      }
    })
}

componentDidMount() {
  this.getLngLat().then(hasData => {
    if (hasData) {
      this.getDistance(
        DriverHomeContents.RiderPickUpLatitude,
        DriverHomeContents.RiderPickUpLongitude,
        DriverHomeContents.RiderDropUpLatitude,
        DriverHomeContents.RiderDropUpLongitude
      );
    }
  })
}
额外注意

你原有代码中调用getDistance时最后一个参数误写为RiderPickUpLongitude,属于笔误,修复时记得替换为下车点经度RiderDropUpLongitude,避免计算距离错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 10:27:04