JavaScript 似乎不等待返回值

标签 javascript asynchronous callback asynccallback

我已经为此苦苦挣扎了一段时间了。我是 Javascript 新手,一直认为我编写的代码是异步运行的。这是一个通用示例:

我在函数 a 中运行一些代码。然后函数 A 调用函数 B,函数 B 需要将变量返回给 A,以便 A 可以在后续操作中使用它。看起来,当 A 调用 B 时,它仍然继续运行自己的代码,而不是等待其返回值而被阻塞,并且 B 的速度不够快,以至于 A 最终到达需要使用返回值的点值,我收到 undefined variable 类型错误

我解决这个问题的方法是让函数 A 调用函数 B,然后函数 B 调用函数 C,该函数 C 将执行 A 将使用返回值执行的后续操作......我正在序列化我的通过调用而不是返回来编写代码...虽然很麻烦...

以下是实际代码中发生这种情况的示例:

function initialize() {
    //Geocode Address to obtin Lat and Long coordinates for the starting point of our map
    geocoder = new google.maps.Geocoder();
    var results = geocode(geocoder);
    makeMap(results[0].geometry.location.lat(), results[0].geometry.location.lng());

}

function geocode(geocoder) {
    //do geocoding here...

    var address = "3630 University Street, Montreal, QC, Canada";
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           return results;
            }
         else {
            alert("Geocode was not successful for the following reason: " + status);
        }
   });

}

function makeMap(lat, long) {
  //  alert(lat); for debuging
    var mapOptions = {
        center: new google.maps.LatLng(lat, long),
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
     map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
}

注意:初始化被我的html中的body onload="initialize()"调用。

所以问题是 makeMap 需要通过 Geocode 函数获得的纬度和经度值,但我在控制台中收到错误消息,指出结果未定义。到底是怎么回事?我来自 Java,所以我对 JS 中的数据流是如何发生的感到有点困惑!这对于 future 来说将是宝贵的教训!

附带问题:我应该如何在外部脚本之间拆分我的函数?什么被认为是好的做法?我应该将所有函数都塞进一个外部 .js 文件中还是应该将类似的函数分组在一起?

最佳答案

您似乎对问题很了解,但似乎不熟悉解决问题的方法。解决此问题的最常见方法是使用回调。这基本上是等待返回值的异步方式。以下是您如何在您的案例中使用它:

function initialize() {
    //Geocode Address to obtin Lat and Long coordinates for the starting point of our map
    geocoder = new google.maps.Geocoder();
    geocode(geocoder, function(results) {
        // This function gets called by the geocode function on success
        makeMap(results[0].geometry.location.lat(), results[0].geometry.location.lng());        
    });
}

function geocode(geocoder, callback) {
    //do geocoding here...

    var address = "3630 University Street, Montreal, QC, Canada";
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            // Call the callback function instead of returning
            callback(results);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
   });

}

...

关于JavaScript 似乎不等待返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13455134/

相关文章:

javascript - 如何使用 javascript/nodejs 从 latin1 (iso-8859-1) 数据库获取数据?

java - 如何让异步tcp服务器继续监听 channel 而不是关闭它

TableView 中的 Facebook 好友列表 : Think need Async Programming?

javascript - 异步对象操作

javascript - NowJS 在失去连接后手动启动新连接

javascript - CSS 和 javascript

python - 如何避免数组在回调后重置?

ruby-on-rails - Ruby method_added 回调不触发包括模块

javascript - 为什么一个 $(document).ready(function() { 会阻止另一个 $(document).ready(function() { 运行?

swift - 如何在 SwiftUI 中异步请求完成后调用函数?