2017-08-18 51 views
0

我想在变量被设置后立即执行一个函数(geoloaction['latitude'])。我不确定下面的代码是否是使用延迟的正确方法。不幸的是,它不工作,因为我希望。当变量被设置然后(等待直到被设置然后执行)

$.when(geolocation['latitude']).then(function(){ 
      console.log('latitude = ' + geolocation['latitude']); 
     }); 

什么是最好/正确的方式等待,直到变量已被设置,然后执行一个函数?

+0

刚刚设置的位置后,您是否可以在代码中没有回调? – Shard

+0

@Shard 1.我对回调不太熟悉。 2.我有两个要加载的外部服务(GeoIP,Google自动完成API)。我想让它们在代码中分开。但是,一旦GeoIP服务完全加载并设置了变量,Google自动填充API函数就需要来自GeoIP服务的一个变量。我不确定回调是否是正确的解决方案。 – alev

+0

[虽然变量未定义 - 等待]可能的重复(https://stackoverflow.com/questions/7307983/while-variable-is-not-defined-wait) –

回答

0

错误使用时:

var d1 = $.Deferred(); 
var d2 = $.Deferred(); 
var d3 = $.Deferred(); 

$.when(d1, d2, d3).done(function (v1, v2, v3) { 
    console.log(v1); // v1 is undefined 
    console.log(v2); // v2 is "abc" 
    console.log(v3); // v3 is an array [ 1, 2, 3, 4, 5 ] 
}); 

d1.resolve(); 
d2.resolve("abc"); 
d3.resolve(1, 2, 3, 4, 5); 

如果你不能说你的代码功能,您可以检查与价值:

setInterval(function(){ 
    if(geolocation['latitude'] != undefined){ 
     console.log('latitude = ' + geolocation['latitude']); 
    } 
}, 1); 
+0

有没有办法做到这一点间隔或超时。也许有一个事件监听器? – alev

+0

取决于您的项目,这种方式肯定有效 –

0

我不想使用时间因为我认为必须有更现代的方法来解决这个问题。所以我在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的代码库就完全分开了,没有什么需要嵌套。

相关问题