How to return the value of a parent function from a nested anonymous function

I have a javascript function that should return geocoding for a string:

function codeAddress(address) { var result = (new google.maps.Geocoder()).geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { return String(results[0].geometry.location.Ya)+','+String(results[0].geometry.location.Za) } else { return status; } }); console.log(result); return result } 

However, it returns "undefined". I understand the error here, that is, since javascript is asynchronous, its return from the codeAddress function(results, status) before the function(results, status) fully executed. But I need to know which solution is here and which is the best.

+4
source share
1 answer

Since it is asynchronous, you must pass a callback that processes the function:

 function codeAddress(address, callback) { (new google.maps.Geocoder()).geocode({ 'address' : address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { callback(String(results[0].geometry.location.Ya) + ',' + String(results[0].geometry.location.Za)) } else { callback(status); } }); } codeAddress("test", function(result) { // do stuff with result }); 

If you use jQuery, you can also use deferred:

 function codeAddress(address, callback) { var dfd = new jQuery.Deferred(); (new google.maps.Geocoder()).geocode({ 'address' : address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { // trigger success dfd.resolve(String(results[0].geometry.location.Ya) + ',' + String(results[0].geometry.location.Za)); } else { // trigger failure dfd.reject(status); } }); return dfd; } codeAddress("some address").then( // success function(result) { // do stuff with result }, // failure function(statusCode) { // handle failure } ); 
+10
source

Source: https://habr.com/ru/post/1302437/


All Articles