How can I catch the return value from the result() callback function that I'm using?

时间秒杀一切 提交于 2019-12-11 23:38:11

问题


<script type="text/javascript">
  var geo = new GClientGeocoder();

  function showAddress() {
    var search = document.getElementById("search").value;
    // getLocations has not ret, so wtf!
    geo.getLocations(search, function (result) { (result.Status.code == 200) ? alert(result.Placemark[0].Point.coordinates) : alert(result.Status.code); });
  }</script>

I need the ret value of the callback as getLocations() returns no values. How can I do this?


回答1:


You can't. You have to write your code in such a way that the code that needs the result value is executed in the callback.

Example (I just named the function in a way which seems logical to me):

function drawPlacemarks(marks) {
   // do fancy stuff with the results
   alert(marks[0].Point.coordinates);
}

function getAddress(callback) {
    var search = document.getElementById("search").value;
    geo.getLocations(search, function (result) { 
        if(result.Status.code == 200) {
           // pass the result to the callback
           callback(result.Placemark);
        }
    });
}

getAddress(drawPlacemarks);


来源:https://stackoverflow.com/questions/5316122/how-can-i-catch-the-return-value-from-the-result-callback-function-that-im-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!