简体   繁体   English

Javascript:返回速度太快,不等待Google Maps API

[英]Javascript: return too fast, doesn't wait on Google Maps API

I want the distance by car and train. 我要乘汽车和火车。 I can get it from the Google Maps API but when I want the distance in a variable, the function getDistance() with the API returns direct and doesn't wait on the response from the API. 我可以从Google Maps API中获取它,但是当我想要一个变量中的距离时,带有API的函数getDistance()会返回直接值,而不必等待API的响应。 On the Internet I found solutions with async/await, promises and callbacks. 在Internet上,我找到了带有异步/等待,承诺和回调的解决方案。 But it doesn't work for me, probably because I wrote it wrong. 但这对我不起作用,可能是因为我写错了。 But can someone please help me and explain my fault? 但是有人可以帮我解释一下我的错吗?

Thanks! 谢谢!

My code: 我的代码:

function giveComparing(result) {
        var $distanceCar = getDistance(result, google.maps.TravelMode.DRIVING);
        var $distanceTrain = getDistance(result, google.maps.TravelMode.TRANSIT);

        console.log($distanceCar); // Output: 0
        console.log($distanceTrain);  // Output: 0

    };

    function getDistance(result, transport) {
        var origin = result.departure.stationinfo.locationY + ',' + result.departure.stationinfo.locationX;
        var destination = result.arrival.stationinfo.locationY + ',' + result.arrival.stationinfo.locationX;
        var service = new google.maps.DistanceMatrixService();
        var distance = 0;

        service.getDistanceMatrix(
            {
                origins: [origin],
                destinations: [destination],
                travelMode: [transport]
            }, callback);

        function callback(response, status) {
            console.log(response.rows[0].elements[0].distance.value);
            distance = response.rows[0].elements[0].distance.value;
        };
        return distance;            
  } 

Output 产量

As you mentioned you are right on point, you do need to use promise and async/await. 正如您提到的那样,您的观点是正确的,您确实需要使用promise和async / await。 A previews question was solved, which are quite similar and well explained here if you want an indepth explanation :) 解决了一个预览问题,如果您需要深入的解释,这非常相似,并且在这里得到了很好的解释:)

You can do the following to achieve the effect you are looking for: 您可以执行以下操作以达到所需的效果:

async function giveComparing(result) {
  try{
    var $distanceCar = await getDistance(result, google.maps.TravelMode.DRIVING); //Wait for the promise to resolve
    var $distanceTrain = await getDistance(result, google.maps.TravelMode.TRANSIT);//Wait for the promise to resolve

    console.log($distanceCar);
    console.log($distanceTrain); 
  }catch(){
    console.log("Promise was rejected") //A promise was rejected.
  }
};

function getDistance(result, transport) {
  return new Promise((resolve, reject) => {
    var origin = result.departure.stationinfo.locationY + ',' + result.departure.stationinfo.locationX;
    var destination = result.arrival.stationinfo.locationY + ',' +      result.arrival.stationinfo.locationX;
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: [transport]
      }, callback);

    function callback(response, status) {
        if(status == "OK"){
            console.log(response.rows[0].elements[0].distance.value);
            let distance = response.rows[0].elements[0].distance.value;
            resolve(distance); //Resolve our promise with the distance.
        }else{
            reject(); //Reject the promise since the status return anything else then OK
        }
    }
  });        
} 

The above code is not directly tested however I think the status OK is correct, found it from their developer guide . 上面的代码没有经过直接测试,但是我认为状态正确是正确的,可以从开发人员指南中找到

You almost had it right. 你几乎是对的。 You can't return a value from an async operation like that so you use a callback, but you pass that callback into getDistance as an argument to be called instead. 您无法从这样的异步操作中返回值,因此您将使用回调,但是会将回调传递 getDistance作为要调用的参数。

function getDistance(result, transport, callback) {

 //... 

  service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: [transport]
  }, callback);
}

// Call getDistance, passing the original arguments
// and a callback function
getDistance(result, transport, function (response) {
  const distance = response.rows[0].elements[0].distance.value;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM