0

I'm working on this vue project where I'm trying to run this function where I use google maps to reverse geocode an address, extract info from that address and run a different function using the modified callback data. I understand that the geocoder function returns a promise and that you can't use the result until the promise is fullfilled, but I'm having trouble getting the rest of my program to wait until the promise has been returned.

my initial setup is like that covered in this question Using a callback function with Google Geocode...

methods:{
        ...mapActions({
        newFunction: "someModule/newFunction",
        }),

        getLocationData(callback) {
              let geocoder = new this.google.maps.Geocoder();
              const latlng = this.mapCenter;   //latitude and longitude positions from elsewhere
              if( geocoder ) {
                geocoder.geocode({ 'location': latlng }, function (results, status) {
                  if( status == this.google.maps.GeocoderStatus.OK ) {
                    callback(results[0].formatted_address);
                  }
                });
              }
            },

      searchLoacal(){
        this.getLocationData(function(locationData) {
           alert(locationData)

         })
      }
}

up until here it works fine, but I'm unsure of how to further extract the callback locationData from inside getLocationData and use it in other functions. ive tried stuff like

async searchLocal(){
     let result =  await this.getLocationData(function(locationData) {
         return locationData
       })
       this.newFunction(result)
}

where the newFunction runs with an input value of null without waiting for the promise to be fullfilled or...

searchLocal(){
      this.getLocationData(function(locationData) {
         this.newFunction(locationData)
       })
    }

where it reads "typerror: unable to read property newFunction of undefined"

I'm wondering how to either make outside functions accessible to the callback from my reverse geocoding function while actually waiting for the result.

thatguy1155
  • 102
  • 1
  • 8
  • When you call the ```return``` statement in your ```searchLocal``` function, no further code inside that function is executed. Hence ```newFunction``` did not get defined. –  May 08 '20 at 07:21
  • but isn't the return statement inside getLocationData? Would it really stop the outside function? – thatguy1155 May 08 '20 at 07:35

1 Answers1

0

I solved my problem by putting the properties of "this" is a separate variable(self) which made all of those methods accessible inside the callback function

searchLocal(){
      let self = this
      this.getLocationData(function(locationData) {
         self.newFunction(locationData)
       })
    }
thatguy1155
  • 102
  • 1
  • 8