回调函数的返回值

returned value from a callback function

我在通过回调函数获取返回值时遇到了一些问题 ("dist" = undefined).....我已经多次尝试获取该值但仍然未定义。但是,我可以从控制台获取它....请有人帮忙!!

calculateDistance = (place, me) => {
        var origin = new window.google.maps.LatLng(
          parseFloat(place.latitude)
          parseFloat(place.longitude)
        );

        var destination = new window.google.maps.LatLng(
          parseFloat(me.latitude),
          parseFloat(me.longitude)
        );

        var service = new window.google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: window.google.maps.TravelMode.DRIVING,
            avoidHighways: false,
            avoidTolls: false,
            unitSystem: window.google.maps.UnitSystem.metric
          },
          function(response, status) {
            if (
              status === "OK" &&
              response.rows[0].elements[0].status !== "ZERO_RESULTS"
            ) {
              let dist = parseFloat(response.rows[0].elements[0].distance.text);
              return dist;
            } else {
              alert("Error: " + status.toString());
            }
          }
        );
      };

您不能将 Google 的函数强制设为 return 您的回调值,因此您最好从回调内部调用另一个函数。

const setDist = (dist) => {
   //persist your dist somehow, maybe setState?
   this.setState({distance: dist});
}

service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.metric
      },
      function(response, status) {
        if (
          status === "OK" &&
          response.rows[0].elements[0].status !== "ZERO_RESULTS"
        ) {
          let dist = parseFloat(response.rows[0].elements[0].distance.text);
          setDist(dist);
        } else {
          alert("Error: " + status.toString());
        }
      }
    );