【问题标题】:Return variable in function from method callback data in same function从同一函数中的方法回调数据返回函数中的变量
【发布时间】:2010-04-14 22:56:08
【问题描述】:

如何返回 codeAddress 函数的 latlon 变量。 return latlon 不起作用,可能是因为范围,但我不确定如何使它起作用。

function codeAddress(addr) { 
       if (geocoder) { 
           geocoder.geocode({ 'address': addr}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                    var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b;  
                    } else {
                       alert("Geocode was not successful for the following reason: " + status);
                   }

       });
     }  
   } 

【问题讨论】:

    标签: javascript function callback return


    【解决方案1】:

    在外层函数中声明一个变量,在内层函数中设置,在外层函数中返回:

    function codeAddress(addr) { 
      var returnCode = false;
      if (geocoder) { 
        geocoder.geocode({ 'address': addr}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b;
            returnCode = true;
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }  
      return returnCode;
    }
    

    注意:这只有在内部函数立即运行时才有效!

    【讨论】:

    • 它可能不会这样做,因为 geocoder.geocode 可能会执行异步方法调用,其中返回结果的唯一方法是通过提供的回调。
    【解决方案2】:

    您不能从codeAddress 返回geocoder.geocode 的结果,因为geocoder.geocode 会将其结果返回给您提供的回调/闭包。您必须继续使用作为参数给定的回调函数codeAddress

    从您的回调中返回给geocoder.geocode 的任何内容返回给geocoder.geocode 在您的应用程序中没有任何意义。您必须从您提供给geocoder.geocode 的回调中调用应用程序中的某些函数。

    这在 API 的 Geocoding Requests 部分进行了解释。

    【讨论】:

    • 谢谢我在 jquery ajax 回调中遇到过很多次,只是今天没有想到。感谢您的大脑提升。
    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多