geocoder.geocode
takes a callback function, executes async, and then calls the callback when it has the results.
This means getLocationName
returns before the callback has been called, and since there's no return statement it returns undefined
.
return results[1].formatted_address;
returns formatted_address
from the callback and NOT from getLocationName
!
(results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
return results[1].formatted_address; //This returns from this callback
}
}
}
This can be demonstrated by the (generally evil) setTimeout
to fake the async request:
function callMe(value) {
setTimeout(function() { return value; }, 3000);
return "This is not the value";
}
var result = callMe("This is the value");
console.log(result);
https://jsfiddle.net/cok3h4tn/1/
You can see "This is not the value" is being printed because return "This is not the value";
is the return, and not return value;
.
Here's the google maps sample for geocoding, you can see how it uses the result in the callback, rather than trying to return it.
Or, here's another example of how to work with the callback:
Take this example code as the starting point.
It doesn't work, but it's a starting point.
function callMe(value) {
setTimeout(function() { return value; }, 3000);
return "This is not the value";
}
var result = callMe("This is the value");
console.log(result);
callMe
is called, then we want to take the result, and do something with it.
We could write this another way, where the "something" we want to do with the result is in it's own function handleResult
.
function handleResult(result) {
console.log(result);
}
function callMe(value) {
setTimeout(function() { return value; }, 3000);
return "This is not the value";
}
var result = callMe("This is the value");
handleResult(result);
Now that's still incorrect because the "wrong" result is still being passed to handleResult
.
So, we need to make a change that will pass the "right" result to handleResult
.
function handleResult(result) {
console.log(result);
}
function callMe(value) {
setTimeout(function() { handleResult(value); }, 3000);
return "This is not the value";
}
callMe("This is the value");
Updated jsfiddle: https://jsfiddle.net/cok3h4tn/4/