0

I'm trying to write a set of functions that call the openstreetmaps API and parse out the country code, then append that to a URL to update window.location. I've figured out how to use async fetch in order to get to the point where I can return the country code properly, but the URL on the reloaded page, instead of showing the country code, says [object%20Promise]. I'm trying to figure out why it's not sending back just the country code and is sending the promise. I've googled and can't seem to find anything about returning a value from an async fetch, so I'm assuming I'm doing something wrong.

<script>
async function countryCode(lat, long)
  {
    
    var buildURL = 'https://nominatim.openstreetmap.org/reverse?lat=' + lat + '&lon=' + long + '&format=json&zoom=3';
    var twoLetterCode = await fetch(buildURL)
        .then(response => {
          return response.json();
      })
        .then(data => {var jsonData = data;
                       var addressInfo = jsonData.address;
                       var code = addressInfo.country_code                           
                       return code;
                      });
    console.log(`Code is: ` + twoLetterCode);   
    return twoLetterCode;
   
  }

function getLocation(){
   navigator.geolocation.getCurrentPosition(function(position) {
    let mapJson = countryCode(position.coords.latitude, position.coords.longitude);
     window.location = window.location.href.split('?')[0] + "?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&loc=" + mapJson;
   });
 
}
</script>
  • `countryCode` is `async` and you're not awaiting its result. – David Jul 16 '21 at 19:01
  • This is what I understand as well. Where I'm running into trouble is that I can't figure out how to do that in this case. The search results I'm finding aren't telling me how to add that wait within the getLocation() function to wait for the results from the countryCode() function. When I use async and await in getLocation(), it throws an error that countryCode is not defined. – Chris Robock Jul 16 '21 at 19:57
  • Either make `getLocation` also `async` and use the `await` keyword on the call to `countryCode` (exactly as you do within `countryCode` itself), or append a `.then()` to the call to `countryCode` and use its result in there. – David Jul 16 '21 at 20:00
  • Thanks David. I had tried that earlier and got the error "Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules" when loading the page, and just now realized that the async should go in front of the function(position) instead of the function getlocation(). problem solved. – Chris Robock Jul 16 '21 at 20:49

0 Answers0