Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return value to parent function from nested anonymous function

I have a javascript function which should return a 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 bug here,i.e, since javascript is asynchronous, its returning from the function codeAddress even before function(results, status) gets fully executed. But I need to know whats the solution here and the best practice.

like image 897
jerrymouse Avatar asked Nov 19 '12 14:11

jerrymouse


1 Answers

Since it's asynchronous, you should pass a callback which handles 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're using jQuery, you could 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
    }
);
like image 60
sroes Avatar answered Oct 31 '22 09:10

sroes