Ankur Verma Ankur Verma - 1 year ago 43
Javascript Question

Returning objects through Asynchronous calls in JavaScript

I am developing a Pure Java program that takes an Address in the form of text and the passes it to Google Map API for further breaking in Country,State and Zip.

But I got stuck somewhere where my Java Program is throwing an exception resulting in awkward results.

Now I decided to use the java integrating it with Rhino.
This is because I successfully developed a Web Page that takes a string and parses it in Country,State and Zip.
So now my thinking is that I will integrate this JavaScript file in my Java file using Rhino.

function showLocation(address) {
var geocoder;
alert("GC is initialised");
geocoder = new GClientGeocoder();

geocoder.getLocations(address , function(response)
if (!response || response.Status.code != 200) {alert("Sorry, unable to locate that address");}
else {
place = response.Placemark[0];
}//end of showLocation

Now my question is that how can I return the object of place when I call showLocations()

Answer Source

You can't! Since getLocations is asynchronous, showLocation has already finished executing before response is available.

You need to accept a callback to showLocation. There are some other problems which I will fix below.

function showLocation(address, callback) {
    var geocoder = new GClientGeocoder(); // no need for !geocoder test--it will always be undefined!

    geocoder.getLocations(address , function(response) {
        if (!response || response.Status.code != 200) {
            alert("Sorry, unable to locate that address");
        } else {
            // you forgot the "var" before "place"--you were making a global variable "place"
            var place = response.Placemark[0];
            if (callback) callback(place);

Then you make the user supply a callback like so:

function placeCallback(place) {
    // do something with place object here
showLocation('my address', placeCallback);