#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Posts
    156
    Rep Power
    20

    await - not quite working


    Perhaps you can shed some light on this for me.

    I've got an async function i'm using to populate two variables before submitting them. I'm not sure what i'm doing wrong here but when i submit my form the variables are undefined. and if i console log directly after this.model.lat it comes up undefined.
    Code:
     async save () {
            this.model.lat = await this.geocodeAddress('lat')
            this.model.lng = await this.geocodeAddress('lng')
    This is the geocodeAddress function
    Code:
    async geocodeAddress (type) {
            var clientAddress = this.model.street + ' ' + this.model.city + ' ' + this.model.province + ' ' + 'Canada'
            var geocoder = new google.maps.Geocoder()
            geocoder.geocode({ 'address': clientAddress }, function (results, status) {
              if (status === 'OK') {
                var lat = results[0].geometry.location.lat()
                var lng = results[0].geometry.location.lng()
                if (type === 'lat') {
                  return lat
                } else if (type === 'lng') {
                  return lng
                }
              } else {
                alert('Geocode was not successful for the following reason: ' + status)
              }
            })
          },
    I thought i was using await in the right way but apparently not. Can somebody help correct what i'm doing wrong here.

    Thanks,
    DSFX
  2. #2
  3. Backwards Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,904
    Rep Power
    9646
    Your geocodeAddress is wrong: you cannot return a value from it if that value is coming from an async callback inside it.

    Use a Promise.

    Comments on this post

    • Paul-Ninja agrees
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Posts
    156
    Rep Power
    20
    Thanks,

    I'm so used to call backs i had to do some reading to get this working. After a brief tussle with my API this is working. Thanks for your help.
    Last edited by dsfx; August 5th, 2018 at 03:39 AM.

IMN logo majestic logo threadwatch logo seochat tools logo