JavaScript 似乎不会等待返回值 [英] JavaScript doesn't seem to wait for return values
问题描述
我已经为此苦苦挣扎了一段时间.我是 Javascript 的新手,一直觉得我编写的代码一直在异步运行.这是一个通用示例:
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:
我在函数 a 中运行了一些代码.然后函数 A 调用函数 B,后者需要将一个变量返回给 A,以便 A 可以在以后的操作中使用它.似乎当 A 调用 B 时,它仍然继续运行自己的代码,而不是等待它的返回值被阻塞,而且 B 的速度不够快,以至于 A 最终达到了它需要使用返回值的程度value 并且我收到未定义的变量类型错误.
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.
我解决这个问题的方法是让函数 A 调用函数 B,然后调用函数 C,该函数将执行 A 将使用返回值执行的后续操作......我有点序列化我的通过调用而不是返回来编写代码……虽然很麻烦……
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...
这是在实际代码中发生时的示例:
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);
}
注意: initialize 被我的 html 中的 body onload="initialize()" 调用.
Note: initialize gets called by body onload="initialize()" in my html.
所以问题是 makeMap 需要通过地理编码函数获得的纬度和经度值,但我在控制台中收到一个错误,说结果未定义.到底是怎么回事?我来自 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屋!