无法访问从 google 距离矩阵函数派生的变量的值

Not able to access value of variable derived from google distance matrix function

我正在使用 Google 距离矩阵 api 来获取两个位置之间的距离。我全局声明了一个变量。在函数中更改了此变量。但按照正常情况,我应该能够在调用我的函数后访问变量的这个更改值。但是现在我无法访问变量的更改值。我的代码是:

var distance = require('google-distance-matrix');

var origins = ['San Francisco CA'];
var destinations = ['New York NY'];

distance.key('My API key');
distance.units('imperial');
// my global variabel
let ourdistance;

function getdistance(){ distance.matrix(origins, destinations, function (err, distances) {
     for (var i=0; i < origins.length; i++) {
            for (var j = 0; j < destinations.length; j++) {
                var origin = distances.origin_addresses[i];
                var destination = distances.destination_addresses[j];
                if (distances.rows[0].elements[j].status == 'OK') {
                    var distance = distances.rows[i].elements[j].distance.text;
                    console.log("This is the distance covered "+ distance);
                    //changing global variable value inside function
                    ourdistance=distance}}}});}

// calling function                    
getdistance();

console.log("finale distance is "+ ourdistance);

我得到的结果是:---- "finale distance is undefined" "This is the distance covered 2,903 mi"

现在我不知道为什么"This is the distance covered 2,903 mi"在前,为什么我不能得到变量

的改变值

这是预期的行为。 console.log("finale distance is "+ ourdistance);getdistance() 完成之前正在执行。 所以,你必须在回调中 console.log

示例:

async function main() {
  const util = require('util');
  const matrix = util.promisify(distance.matrix);

  async function getdistance() {
    let ourdistance;
    const distances = await matrix(origins, destinations);
    for (var i = 0; i < origins.length; i++) {
      for (var j = 0; j < destinations.length; j++) {
        var origin = distances.origin_addresses[i];
        var destination = distances.destination_addresses[j];
        if (distances.rows[0].elements[j].status == 'OK') {
          var distance = distances.rows[i].elements[j].distance.text;
          console.log("This is the distance covered " + distance);
          ourdistance = distance
        }
      }
    }

    return ourdistance;
  }

  // calling function                    
  let ourdistance = await getdistance();

  console.log("finale distance is " + ourdistance);
}

main();