async-await not working when exporting Google distance Matrix from a class

元气小坏坏 提交于 2020-01-25 09:18:06

问题


I'm using the google places autocomplete and the Distance Matrix to put two locations in and print out the distance between the two. I have two javascript es6 classes to separate the Google API's as services.

My problem is I'm trying to await the response on getting the distance from the distance matrix service then log it to the console, but I get undefined when I log it. the distance matrix service is returning the response after I log it. This must mean that my await in the method is not working. What am I doing wrong?

distanceMatrix.js

export default class DistanceMatrixService {
    constructor(pickup, dropoff, garage){
        .....
        }

    getDistance(arg1, arg2) {
        this.distance.getDistanceMatrix({
        origins: [arg1],
        destinations: [arg2],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.IMPERIAL
      }, response => {
          console.log(response) //actually returns desired response
          return response.rows[0].elements[0].distance.text}
    );
 }

main.js

calcButton.addEventListener('click', async (event) => {
    event.preventDefault();

    const distanceMatrix = new DistanceMatrixService(pickupInfo.formatted_address, dropoffInfo.formatted_address)
    const pickup =  pickupInfo.formatted_address
    const dropoff = dropoffInfo.formatted_address

    const ptd = await distanceMatrix.getDistance(pickup, dropoff);

    console.log(ptd) // undefined
 });

I expect the console.log(ptd) to wait for distanceMatrix.getDistance() to finish, but the actual results is ptd is logged as undefined then console.log(response) from the distance matrix is logged out next. This should be the other way around.


回答1:


async/await works with promises and will not work with a callback. Try the following instead by returning a promise from getDistance() and resolving the respective value from within the callback:

export default class DistanceMatrixService {
  constructor(pickup, dropoff, garage) { /* ... */ }

  getDistance(arg1, arg2) {
    return new Promise((resolve, reject) => {
      this.distance.getDistanceMatrix({
        origins: [arg1],
        destinations: [arg2],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.IMPERIAL
      }, response => {
        console.log(response) //actually returns desired response
        resolve(response.rows[0].elements[0].distance.text);
      }
      );
    });
  }
}

You should consider using catch() as well to handle errors as necessary.

Hopefully that helps!



来源:https://stackoverflow.com/questions/54727221/async-await-not-working-when-exporting-google-distance-matrix-from-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!