0

I was trying to fetch some JSON data from a google map API. When I called this function, I want the "test" variable to become 45. But it is still 0.
This following code looks a little bit stupid because I want to simplify things. I have a valid API key please don't question that. Did I misunderstand Javascript or the fetch api or something? Please help.. Thanks a lot!

function toLat(location) {
    var lat = 0;
    if (location.length > 0) {
        var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address=Seattle&key=Your_API_Key";
        fetch(googleURL)
            .then(function(response) {
                return response.json();
             })
            .then(function(data) {
                data.results.forEach(function(item) {
                    lat = item.geometry.location.lat;
                });
                console.log(lat);    // here is, e.g. '45'
            });
    }
    return lat;
}
var test = toLat();
console.log(test);    // why still '0'?
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Emile
  • 187
  • 5
  • 17
  • 2
    `fetch` is asynchronous. `toLat` returns immediately. – bejado Mar 09 '17 at 03:29
  • 1
    You need to understand asynchronous code. The rest of your code continues to run while the JSON data is being pulled in. As such, your return statement is useless. You will need to put code that depends on the value where you have your console.log statement. – Lee Taylor Mar 09 '17 at 03:29
  • @LeeTaylor Thanks for the explanation! So it is not possible to take out the value to use at elsewhere? – Emile Mar 09 '17 at 03:35
  • 1
    @Emile. You need to put the code that relies on that value into the function that is called when the data is received (like you have with the .log statement). So it will required a different way of thinking and coding. – Lee Taylor Mar 09 '17 at 03:39

1 Answers1

1

The fetch api returns a Promise. This is a asynchronous procedure, so you need to update the value of test here:

then(function(data){ // here })