1

I have the following code:

var sLat = "test"; //global var, set outside any function

...

geocoder.geocode({
    'address': address
}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        alert(sLat); //SHOWS test, THATS OK
        sLat = "test2"; //TRYING TO CHANGE ITS VALUE
    } else {
        alert('Geocode was not successful for the following reason: ' + status);
    }
});
alert(sLat); // SHOWS test INSTEAD OF test2

The problem is that the var is accessible inside the callback function but when I try to change its value, the new value ("test2") isn't saved. Whats the problem?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
ruda
  • 181
  • 4
  • 14
  • 1
    When the callback it's called the value of the variable changes. The problem it's that you are alerting the value before it changes (i.e., before the callback it's called). – sergioFC Aug 05 '14 at 18:22

1 Answers1

4

You actually are changing the variable, but when you do it in a callback, this process is asynchronous, so the last line is excecuted before the code inside the callback is excecuted.

You have to make a promise so it waits for the callback to return before excecuting the rest of the code.

Look at this examples:

Promise & Deferred Objects in Javascript

guanguer
  • 56
  • 1