[英]getting a value from a callback function
我正在尝试从回调 function 返回一个值并将其分配给一个变量,尽管我正在努力解决它 - 任何帮助都会非常感激......
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;
}
我很困惑,您是否希望回调能够访问coords
值,或者只是从getLocation
function 返回它。如果只是让coords
可用于回调,则将其作为参数传递。
function getLocation(callback) {
navigator.geolocation.getCurrentPosition (function (position){
var coords = position.coords.latitude + "," + position.coords.longitude;
callback(coords);
})
}
getLocation (function(coords){
alert(coords);
})
另一方面,如果要将它分配给getLocation
的返回值,那是不可能的。 getCurrentPosition
API 是异步的,因此您不能从getLocation
方法同步返回它。 相反,您需要传回想要使用coords
的回调。
编辑
OP 说他们只想要latlng1
中的coords
值。 这是你如何做到这一点
var latlng1;
function getLocation() {
navigator.geolocation.getCurrentPosition (function (position){
var coords = position.coords.latitude + "," + position.coords.longitude;
latlng1 = coords;
})
}
请注意,尽管这不会更改 API 的异步性质。在异步调用完成之前,变量latlng1
不会具有coords
值。 因为这个版本不使用回调你无法知道什么时候完成(除了检查latlng1
undefined
怎么样:
var latlng1;
function getLocation(){
navigator.geolocation.getCurrentPosition (function (position){
latlng1 = position.coords.latitude + "," + position.coords.longitude;
callback();
})
}
getLocation (function(){
alert(latlng1);
})
您可以将坐标传递给回调调用,并在回调中为其定义一个参数。 阅读比尝试解释更容易:
var latlng1;
function getLocation(callback){
navigator.geolocation.getCurrentPosition (function (position){
coords = position.coords.latitude + "," + position.coords.longitude;
callback(coords);
})
}
//how can I assign the coords value from the callback to variable latlng1 with global scope?
getLocation (function(coords){
//alert(coords);
return coords;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.