geolocation.getCurrentPosition 如何返回值?

hei*_*hei 6 javascript asynchronous geolocation

我正在使用 getCurrentPosition 来获取当地的纬度和经度。我知道这个函数是异步的,只是想知道如何返回其他函数可以访问的纬度和经度值?

    function getGeo() {
        navigator.geolocation.getCurrentPosition(getCurrentLoc)
    }

    function getCurrentLoc(data) {
        var lat,lon;
        lat=data.coords.latitude;
        lon=data.coords.longitude;
        getLocalWeather(lat,lon)
        initMap(lat,lon)
    }
Run Code Online (Sandbox Code Playgroud)

Der*_*會功夫 15

我建议你把它包装在一个承诺中:

function getPosition() {
    // Simple wrapper
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
}

async function main() {
    var position = await getPosition();  // wait for getPosition to complete
    console.log(position);
}

main();
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/DerekL/zr8L57sL/

ES6版本:

function getPosition() {
    // Simple wrapper
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
}

function main() {
    getPosition().then(console.log); // wait for getPosition to complete
}

main();
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/DerekL/90129LoL/