1

我有一个名为 Location 的类对象,它与 Google 一起使用,以便对给定地址进行地理编码。地理编码请求是通过 AJAX 调用发出的,并通过回调处理,一旦响应到达,该回调将启动类成员。

这是代码:

function Location(address) {
    this.geo = new GClientGeocoder();
    this.address = address;
    this.coord = [];

    var geoCallback = function(result) {
        this.coord[0] = result.Placemark[0].Point.coordinates[1];
        this.coord[1] = result.Placemark[0].Point.coordinates[0];
        window.alert("I am in geoCallback() lat: " + this.coord[0] + "; lon: " + this.coord[1]);
    }

    this.geo.getLocations(this.address, bind(this, geoCallback));                   
}
Location.prototype.getAddress = function() { return this.address; }
Location.prototype.getLat = function() { return this.coord[0] }
Location.prototype.getLng = function() { return this.coord[1] }

我的问题是:在退出构造函数之前可以等待谷歌的响应吗?

我无法控制 AJAX 请求,因为它是通过 Google API 生成的。

我想确保this.coord[]在创建 Location obj 后正确初始化。

谢谢!

4

2 回答 2

3

不,你不能(阅读:不应该)等待。这就是为什么它首先被称为 AJAX(“Asynchronous Javascript ...”)。;)

您可以自己使用回调函数(前面未经测试的代码)。

function Location(address, readyCallback) {
  this.geo = new GClientGeocoder();
  this.address = address;
  this.coord = [];
  this.onready = readyCallback;

  this.geo.getLocations(this.address, bind(this, function(result) {
    this.coord[0] = result.Placemark[0].Point.coordinates[1];
    this.coord[1] = result.Placemark[0].Point.coordinates[0];
    if (typeof this.onready == "function") this.onready.apply(this);
  }));
}
Location.prototype.getAddress = function() { return this.address; }
Location.prototype.getLat = function() { return this.coord[0] }
Location.prototype.getLng = function() { return this.coord[1] }

// ... later ...

var l = new Location("Googleplex, Mountain View", function() {
  alert(this.getLat());
});
于 2010-04-19T17:22:49.870 回答
0

是否可以在退出构造函数之前等待 Google 的响应?

我不会推荐这种方法。创建 JavaScript 对象时,您通常不会期望它阻塞数百毫秒,直到 Google 做出响应。

此外,GClientGeocoder如果您尝试执行频繁的请求,Google 会限制您的请求(来源)。客户在 24 小时内可以执行的请求数量也有上限。使用这种方法系统地处理这将是复杂的。如果您的 JavaScript 对象会随机失败,您很容易陷入调试噩梦。

于 2010-04-19T17:14:51.050 回答