简体   繁体   English

从距离矩阵回调 function 未定义返回值?

[英]Returning a value from distancematrix callback function undefined?

I assume because it is asynchronous.我假设是因为它是异步的。 Here is my code:这是我的代码:

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;
                  }
                }
            }

What I want to do is return the distance and duration values from the callback.我想要做的是从回调中返回距离和持续时间值。 Then, return that value, and feed it to the function that calls the parent function of my above code.然后,返回该值,并将其提供给调用上述代码的父 function 的 function。 What my brute force idea was was to return from within the callback, then return that received value from outside the callback function, so I can actually use the value.我的蛮力想法是从回调内部返回,然后从回调 function 外部返回接收到的值,这样我就可以实际使用该值。 For sake of clarity, here is a diagram, as I understand, of my functions:为了清楚起见,据我所知,这是我的功能的图表:

get_avg_speed
    get_distance
       callback

I know callbacks are async, is there a correct way to do this?我知道回调是异步的,有正确的方法吗?

Promise is your friend here. Promise是您的朋友。 Here's your code using the Promise constructor.这是您使用 Promise 构造函数的代码。 Binary callbacks like these are troublesome, so I put response and status in an object.像这样的二进制回调很麻烦,所以我将responsestatus放在 object 中。

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
}

Then you can use these promise returning functions like this然后你可以像这样使用这些 promise 返回函数

const get_avg_speed = async (...args) => {
/* ... */
  const elementsDistanceDuration = await promisifiedGetDistanceMatrix({
    origins: [yourPosition],
    destinations: [end],
    travelMode: 'WALKING',
  }).then(getElementsDistanceDuration)
}

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

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