JavaScript的似乎并不等待返回值 [英] JavaScript doesn't seem to wait for return values

查看:166
本文介绍了JavaScript的似乎并不等待返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在挣扎了一会儿。我是新来的Javascript,并已使code我已经写了异步运行IM pression下。这是一个普通的例子:

I've been struggling with this for a while now. I'm new to Javascript, and have been under the impression that the code I've been writing has been running asynchronously. Here is a generic example:

我运行功能的一些code。功能A然后调用函数B,谁需要一个变量回归A因此A可以在以后的操作中使用它。看来虽然当A呼叫B时,它仍继续运行它自己的code,不等待阻塞其返回值,以及B是不够快使得A结束到达那里将需要对点使用返回值,我得到的未定义的变量类型错误

I run some code in function a. Function A then calls Function B, who needs to return a variable to A so A can use it in its later operations. It seems though that when A calls B, it still continues to run its own code, not waiting blocked for its return value, and B isn't fast enough such that A ends up reaching the point where it would have needed to use the return value and I get an undefined variable type error.

我身边有这样的工作方式是有函数的调用函数B,然后调用一个函数C,会做什么,以后的操作是A将与返回值做....我是那种序列化的我通过电话,而不是收益code ......这很麻烦,虽然...

The way I have worked around this is have function A call Function B which then calls a Function C that would do what the later operations that A would be doing with the return value....I'm kind of serializing my code through calls instead of returns...that is cumbersome though...

下面是当它在实际code发生的例子:

Here is an example of when it happens in actual code:

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

注意:初始化得到由身体的onload =叫初始化()在我的HTML

Note: initialize gets called by body onload="initialize()" in my html.

所以,问题是,makeMap需要由地理code函数获得的纬度和经度值,但我在控制台说结果得到一个错误是不确定的。到底是怎么回事?我从Java来了,所以我有点困惑的数据流是如何发生在这里的JS!这将是未来的宝贵经验!

So the issue is that the makeMap requires the lat and longitude values obtained by the Geocode function, but I get an error in the console saying results is undefined. What is going on? I came from Java so I'm a little confused about how data flow is happening here in JS! This will be valuable lessons for the future!

在一个侧面的问题:如何,我应该在整个外部脚本拆我的功能呢?什么是好的做法?应我的所有功能塞进一个外部.js文件或者我应该像组功能于一体?

On a side question: How should I split my functions across external scripts? What is considered good practice? should all my functions be crammed into one external .js file or should I group like functions together?

推荐答案

您似乎有问题有很好的理解,但它听起来像是你不熟悉的,解决的方式。解决这一问题的最普通的方式是通过使用一个回调。这基本上是异步的方式来等待一个返回值。这里是你怎么能在你的情况下使用它:

You seem to have a good understanding of the problem, but it sounds like you aren't familiar with the way to solve it. The most common way to address this is by using a callback. This is basically the async way to wait for a return value. Here's how you could use it in your case:

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的似乎并不等待返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆