简体   繁体   English

如何获取成功回调函数结果的赋值给变量

[英]How can I get assign value of success callback function result to a variable

I want to return "currentLoc". 我想返回“ currentLoc”。 Unfortunately, it doesn't work for me. 不幸的是,它对我不起作用。 How is it possible to assign result of callback function to reuse it all through my code. 如何通过我的代码分配回调函数的结果以重用它。

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;

} }

because the callback is happening asynchronously, your return statement happens before the success is ever even run. 因为回调是异步发生的,所以您的return语句会在success运行之前发生。

an option would be to have your main currentLocation function take a callback, and call that with the value from inside success . 一种选择是让您的主要currentLocation函数进行回调,并使用success内部的值进行调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM