gpt4 book ai didi

javascript - 如何将成功回调函数结果的值分配给变量

转载 作者:行者123 更新时间:2023-12-03 04:26:00 25 4
gpt4 key购买 nike

我想返回“currentLoc”。不幸的是,它对我不起作用。如何分配回调函数的结果以在我的代码中重用它?

function currentLocation() {

var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};

function success(pos) {
var crd = pos.coords;
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);

currentLoc = new google.maps.LatLng( crd.latitude, crd.longitude);

};

function error(err) {
///ERROR

};

if ( navigator.geolocation)
navigator.geolocation.getCurrentPosition(success, error, options);

return currentLoc;

}

最佳答案

因为回调是异步发生的,所以您的 return 语句会在 success 运行之前发生。

一个选项是让您的主 currentLocation 函数接受回调,并使用 success 内部的值调用该函数。

关于javascript - 如何将成功回调函数结果的值分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43726189/

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