javascript - How to return value from an asynchronous callback function? -
this question has answer here:
- how return response asynchronous call? 24 answers
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
Post a Comment