0

I have this function. I seem not to understand how it exactly works. Because I want to return returnlatlang with this function. But it simply does not work.

var geocoder = new google.maps.Geocoder();

function codeAddress(address) {
    var returnlatlang;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            returnlatlang = results[0].geometry.location;
            console.log(returnlatlang); // this is defined.
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
    console.log(returnlatlang); // this is undefined.
    return returnlatlang;
}

How does scope work in this case?

Grzegorz
  • 3,538
  • 4
  • 29
  • 47
  • 1
    This is not about scope, but execution time. – IvoC Mar 04 '15 at 00:52
  • Callback is executed asynchronously? So it can finish after i return value? – Grzegorz Mar 04 '15 at 00:57
  • returnlatlang result will be return after the codeAddress function, but the real value should be gotted by the callback function. So you can not get it now. You should define a callback function ,in the callback function you use the returnlatlang , and set the callback to be invoked in the geocode callback function. – Feng Lin Mar 04 '15 at 00:57
  • Here's a good explanation http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Jasen Mar 04 '15 at 00:57

1 Answers1

0

codeAddress returns the variable returnlatlong before the async function is able to set it.

You could use a Promise, a basic example would go something like this:

function codeAddress(address){
    return new Promise(function(resolve, reject){    
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            returnlatlang = results[0].geometry.location;
            resolve(returnlatlang); // this is defined.
        } else {
            reject('Geocode was not successful for the following reason: ' + status);
        }
    });
}
codeAddress('some address').then(function(){
   //the promise resolved
}, function(){
   //the promise rejected
});
Dave
  • 723
  • 7
  • 19