javascript - How to return value from an asynchronous callback function? -


this question has answer here:

this question asked many times in so. still can't stuff.

i want value callback. @ script below clarification.

function foo(address){        // google map stuff       geocoder.geocode( { 'address': address}, function(results, status) {           results[0].geometry.location; // want return value       })      }     foo(); //result should results[0].geometry.location; value 

if try return value getting "undefined". followed ideas so, 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 impossible cannot return asynchronous call inside synchronous method.

in case need pass callback foo receive return value

function foo(address, fn){   geocoder.geocode( { 'address': address}, function(results, status) {      fn(results[0].geometry.location);    }); }  foo("address", function(location){   alert(location); // return value }); 

the thing is, if inner function call asynchronous, functions 'wrapping' call must asynchronous in order 'return' response.

if have lot of callbacks might consider taking plunge , use promise library q.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -