How can I catch the return value from the result()

2019-08-22 21:01发布

问题:

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