-1

I'm wrote a function (with the help of this tutorial https://www.youtube.com/watch?v=pRiQeo17u6c) to geocode addresses using google maps. I want the function to return coordinates of any given address. Eventually, I'm hoping to write a script that loops over an array of addresses and returns a array of their coordinates in the form of [lat, lng].

However, before we go to fast, this question is simply about returning one value. Please see the script below.

The function works. If I for example call geocode('New York') and enable console.log(latlng) within the function, it properly logs [40.7127753,-74.0059728]. However, if I call the function to appoint a variable like var coord_address_1 = geocode("New York") this variable is undefined. What am I doing wrong? I have read these posts How do I return the response from an asynchronous call? and concluded that it has probably to do with the fact that I want latlng returned before it is assigned. However, as I am new to JS I didn't really understand how to avoid this. I tried around with .then(function(latlng) {return latlng;}) and callback(latlng); but no luck there either (ReferenceError: callback is not defined).

    <script>
      function geocode(address) {
        axios
          .get("https://maps.googleapis.com/maps/api/geocode/json", {
            params: {
              address: address,
              key: "API_KEY"
            }
          })
          .then(function(response) {
            // create variable in desired format
            var latlng =
              "[" +
              [
                response.data.results[0].geometry.location.lat,
                response.data.results[0].geometry.location.lng
              ] +
              "]";

            // this works
            // console.log(latlng);

            return latlng;

          })
          .catch(function(error) {
            console.log(error);
          });
      }

      var coord_address_1 = geocode("New York");
      console.log(coord_address_1); // undefined
    </script>
Peter
  • 343
  • 5
  • 17
  • 3
    This question ( https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call ) is indeed the way to go. Yours will likely be closed because it's a duplicate, it's the exact same problem. This question was asked by pretty much everyone learning JS and stumbling upon asynchronism. – Jeremy Thille May 06 '20 at 15:05
  • Either return the promise, or pass in a callback and invoke that with the values. – jonrsharpe May 06 '20 at 15:06
  • Basically, instead of `return latlng` which returns the value to nothing (dead end), pass the value to another function. `doSomethingWith(latlng)` – Jeremy Thille May 06 '20 at 15:06
  • Imagine that `geocode("New York")` takes 3 seconds. Javascript is non-blocking, meaning it's not going to block the whole script for 3 seconds waiting for the answer. It jumps _immediately_ to the next line `console.log()` which logs undefined, because the instruction above is far from complete. It will be complete in 3 seconds, and you will have your result in the `.then()`. Returning the value won't do anything, it's too late. You need to pass it forward. Welcome to asynchronism :) – Jeremy Thille May 06 '20 at 15:12
  • Alright guys, thanks for your quick responses! Ill have another go at understanding asynchronism :) So it's not as simple as adding `.then(function(latlng) {return latlng; })` between the first `.then()` and the `.catch()`? – Peter May 06 '20 at 15:26

1 Answers1

0

When using a promise, since the .then() is technically a method of the promise, any return inside the method actually returns for the .then() method, not the function outside.

Someone else had a similar problem here.

If you want to return the value from the function, you have to have your return statement outside of the promise's .then() or .catch() methods.

Another thing you need to consider is that the promise will not return immediately as it is asynchronous, link from Jeremy Thille's comment

dwb
  • 2,136
  • 13
  • 27