从回调函数JSON返回一个值

时间:2015-04-14 02:26:59

标签: javascript jquery json callback asynccallback

我有以下示例代码来调用映射服务来计算两个Geocodes(Waypoint)之间的距离。我想从服务中获得返回的距离。但是,我似乎无法将其置于foo函数的范围之外。我是否必须使用Closure或Promise或JQuery。我对JQuery和Closure / Promises的有限知识意味着重写这个例子。

    var service = new EMS.Service.Route();  //this is a whereIS JSON Service, it's asynchronous 
    var output = document.getElementById("Result");
    var html = "blah";
    var waypoints = [];
    waypoints.push({"lon": 144.963165, "lat": -37.814251}); //Melbourne GeoCode
    waypoints.push({"lon": 151.160838, "lat": -33.879643}); //Sydney Geocode

    window.onload = function() {    
        service.route(waypoints,foo);   // foo back is a callback function
        alert(html);    //would like to return the results of the asynchronous service outside of the foo function but its always "blah" (as defined in the global variable)
        }

    function foo(response) {
                    html =  Math.round((response.route.distance/1000)*100)/100 +  "<br>";
                    output.innerHTML = html;
                    return html
        }

0 个答案:

没有答案