在JavaScript中通过异步调用返回对象

Returning objects through Asynchronous calls in JavaScript

本文关键字:调用 返回 对象 异步 JavaScript      更新时间:2023-09-26

我正在开发一个纯Java程序,它以文本的形式接受地址并将其传递给Google Map API以进一步打破国家,州和Zip

但是我被困在某个地方,我的Java程序抛出一个异常,导致尴尬的结果。

现在我决定使用java与Rhino集成。这是因为我成功地开发了一个Web Page,它接受字符串并以Country,State和Zip格式解析它。所以现在我的想法是,我将这个JavaScript文件集成到我的Java文件使用Rhino。

           function showLocation(address) {
                var geocoder;
                if(!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 CALLBACK METHOD
                );//END OF GETLOCATIONS
           }//end of showLocation

现在我的问题是,当我调用showLocations()

时,如何返回place的对象

你不能!由于getLocations是异步的,在response可用之前,showLocation已经完成了执行。

您需要接受showLocation的回调。还有一些其他的问题,我将在下面解决。

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);
        }
    });
}

然后让用户提供一个回调,如下所示:

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