1 javascript anonymous function callback
我正在尝试从回调函数返回一个值并将其分配给一个变量,尽管我正在努力解决这个问题 - 任何帮助将非常感激......
var latlng1;
function getLocation(){
navigator.geolocation.getCurrentPosition (function (position){
coords = position.coords.latitude + "," + position.coords.longitude;
callback();
})
}
//how can I assign the coords value from the callback to variable latlng1 with global scope?
getLocation (function(){
//alert(coords);
return coords;
})
// -----------
//I'm trying something like this....but no joy
latlng1 = getLocation (function(){
return coords;
}
Run Code Online (Sandbox Code Playgroud)
我很困惑您是否希望回调能够访问该coords
值或只是从getLocation
函数返回它。如果只是为了coords
回调可用,则将其作为参数传递。
function getLocation(callback) {
navigator.geolocation.getCurrentPosition (function (position){
var coords = position.coords.latitude + "," + position.coords.longitude;
callback(coords);
})
}
getLocation (function(coords){
alert(coords);
})
Run Code Online (Sandbox Code Playgroud)
另一方面,如果要将其分配给 returngetLocation
则这是不可能的。该getCurrentPosition
API 是异步的,因此您无法从该getLocation
方法同步返回它。相反,您需要传递想要使用的回调coords
。
编辑
OP 说他们只想要coords
中的值latlng1
。这是实现这一目标的方法
var latlng1;
function getLocation() {
navigator.geolocation.getCurrentPosition (function (position){
var coords = position.coords.latitude + "," + position.coords.longitude;
latlng1 = coords;
})
}
Run Code Online (Sandbox Code Playgroud)
但请注意,这不会改变 API 的异步性质。在异步调用完成之前,该变量latlng1
不会有值。coords
因为此版本不使用回调,所以您无法知道何时完成(除了latlng1
检查undefined