我不想使用时间因为我认为必须有更现代的方法来解决这个问题。所以我在stackoverflow上找到了另一个有趣的解决方案,它让我可以将一个事件监听器附加到一个变量上,并在变量设置完成后执行我的代码。
https://stackoverflow.com/a/37403125/4688612
我的解决方案,现在看起来是这样的:
在我的地理位置脚本我安装一个变量(经度和纬度)与事件侦听器。
geolocation = {
latlonInternal: '',
latlonListener: function(val) {},
set latlon(val) {
this.latlonInternal = val;
this.latlonListener(val);
},
get latlon() {
return this.latlonInternal;
},
registerListener: function(listener) {
this.latlonListener = listener;
}
}
在我的Google Places自动填充API中,我注册了侦听器,并等到变量设置完毕。
geolocation.registerListener(function(val){
console.log('latitude = ' + val[0]);
console.log('longitude = ' + val[1]);
});
一旦地理位置服务检索到位置,它将更新地理位置变量并触发侦听器。
geolocation.lonlat = [ geoipResponse.location.latitude, geoipResponse.location.longitude ];
这样我的GeoIP和Google Paces自动完成API的代码库就完全分开了,没有什么需要嵌套。
刚刚设置的位置后,您是否可以在代码中没有回调? – Shard
@Shard 1.我对回调不太熟悉。 2.我有两个要加载的外部服务(GeoIP,Google自动完成API)。我想让它们在代码中分开。但是,一旦GeoIP服务完全加载并设置了变量,Google自动填充API函数就需要来自GeoIP服务的一个变量。我不确定回调是否是正确的解决方案。 – alev
[虽然变量未定义 - 等待]可能的重复(https://stackoverflow.com/questions/7307983/while-variable-is-not-defined-wait) –