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

node.js - How to mock a third-party api calls in the backend -

node.js - Why do I get "SOCKS connection failed. Connection not allowed by ruleset" for some .onion sites? -

matlab - 0-by-1 sym - What do I need to change in order to get proper symbolic results? -