How to return value from an asynchronous callback function? [duplicate]

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

3 s
3

Leave a Comment