从distancematrix回调函数返回值未定义?

问题描述 投票:0回答:1

我想是因为它是异步的。这是我的代码:

service.getDistanceMatrix(
        {
            origins: [yourPosition],
            destinations: [end],
            travelMode: 'WALKING',
        }, callback);

        function callback(response, status) {
            if (status == 'OK') {
                var origins = response.originAddresses;
                for (var i = 0; i < origins.length; i++) {
                  var results = response.rows[i].elements;
                  for (var j = 0; j < results.length; j++) {
                    var element = results[j];
                    var distance = element.distance.value;
                    var duration = element.duration.value;
                  }
                }
            }

我想做的是从回调中返回距离和持续时间值。然后,返回该值,并将其提供给调用上述代码的父函数的函数。我的暴力想法是从回调内部返回,然后从回调函数外部返回接收到的值,因此我可以实际使用该值。为了清楚起见,据我了解,这是我的功能的图表:

get_avg_speed
    get_distance
       callback

我知道回调是异步的,有正确的方法吗?

javascript google-distancematrix-api
1个回答
0
投票

Promise是您的朋友在这里。这是使用Promise构造函数的代码。这样的二进制回调很麻烦,因此我将responsestatus放在对象中。

const promisifiedGetDistanceMatrix = params => new Promise(resolve => {
  service.getDistanceMatrix(params, (response, status) => {
    resolve({ response, status })
  })
})

const getElementsDistanceDuration = ({ response, status }) => {
  if (status !== 'OK') return []
  let elements = []
  let origins = response.originAddresses;
  for (let i = 0; i < origins.length; i++) {
    let results = response.rows[i].elements;
    for (let j = 0; j < results.length; j++) {
      let element = results[j];
      let distance = element.distance.value;
      let duration = element.duration.value;
      elements.push({ distance, duration })
    }
  }
  return elements
}

然后,您可以使用这些像这样的promise返回函数

const get_avg_speed = async (...args) => {
/* ... */
  const elementsDistanceDuration = await promisifiedGetDistanceMatrix({
    origins: [yourPosition],
    destinations: [end],
    travelMode: 'WALKING',
  }).then(getElementsDistanceDuration)
}
© www.soinside.com 2019 - 2024. All rights reserved.