【问题标题】:Wait for firebase fetch to finish before calling another function在调用另一个函数之前等待 firebase fetch 完成
【发布时间】:2021-05-29 14:47:00
【问题描述】:

我正在从 Firebase 检索一些数据(纬度和经度),我想在另一个函数 getDistance() 中使用它。

现在,在调用第二个函数时,我还没有第一个函数的结果。 如何修改代码,以便仅在第一个函数完成后调用第二个函数?

getLngLat = async () => {
    driverId = firebase.auth().currentUser.uid;
    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();
          );
        } else {
          this.toast.show("No ride requests", 500);
        }
      })

componentDidMount() {
this.getLngLat() ;   //first function

this.getDistance(DriverHomeContents.RiderPickUpLatitude,      //second function
DriverHomeContents.RiderPickUpLongitude,
DriverHomeContents.RiderDropUpLatitude,
DriverHomeContents.RiderPickUpLongitude)
}

【问题讨论】:

  • 所以你想等待,但你不使用await关键字?

标签: javascript firebase react-native asynchronous


【解决方案1】:

不会撒谎,你这样做的方式有点奇怪,但无论如何。您必须等待您的函数调用。你应该在 async/await 上查看MDN docs

getLngLat = async () => {
    driverId = firebase.auth().currentUser.uid;

    // IMPORTANT: This async call must be awaited
    await 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();
          );
        } else {
          this.toast.show("No ride requests", 500);
        }
      })
}

async componentDidMount() {
  // You have to await this first
  // this.getRiderRequestDetails();   //first function
  // You should do something like this
  await this.getLngLat()

  this.getDistance(DriverHomeContents.RiderPickUpLatitude,      //second function
  DriverHomeContents.RiderPickUpLongitude,
  DriverHomeContents.RiderDropUpLatitude,
  DriverHomeContents.RiderPickUpLongitude)
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多