This question is asked many times in SO. But still I can't get stuff.
I want to get some value from callback. Look at the script below for clarification.
function foo(address){
// google map stuff
geocoder.geocode( { 'address': address}, function(results, status) {
results[0].geometry.location; // I want to return this value
})
}
foo(); //result should be results[0].geometry.location; value
If I try to return that value just getting "undefined". I followed some ideas from SO, but still fails.
Those are:
function foo(address){
var returnvalue;
geocoder.geocode( { 'address': address}, function(results, status) {
returnvalue = results[0].geometry.location;
})
return returnvalue;
}
foo(); //still undefined
This question is related to
javascript
asynchronous
callback
javascript-objects
If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/
It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.
It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.
Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.
Source: Stackoverflow.com