gpt4 book ai didi

javascript - 从回调函数中获取值

转载 作者:行者123 更新时间:2023-11-30 13:21:33 26 4
gpt4 key购买 nike

我正在尝试从回调函数返回一个值并将其分配给一个变量,尽管我正在努力解决这个问题 - 非常感谢任何帮助....

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 函数中返回它。如果只是让 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

关于javascript - 从回调函数中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com