Javascript 等待getCurrentPosition()不工作

Javascript 等待getCurrentPosition()不工作,javascript,api,Javascript,Api,我正在使用navigator.geolocation.getCurrentPosition()编写点击按钮事件,以获取本地化信息,然后使用我刚刚获得的经度和纬度从openweathermap.org获取信息。 我的问题是,我无法找到让代码等待接收坐标,然后进行提取的方法,这会导致错误,因为要从中提取的链接无效。我知道我应该做一个函数等待,但我完全不知道如何做 locate.addEventListener("click", function () { locateBu

我正在使用navigator.geolocation.getCurrentPosition()编写点击按钮事件,以获取本地化信息,然后使用我刚刚获得的经度和纬度从openweathermap.org获取信息。
我的问题是,我无法找到让代码等待接收坐标,然后进行提取的方法,这会导致错误,因为要从中提取的链接无效。我知道我应该做一个函数等待,但我完全不知道如何做

locate.addEventListener("click", function () {
    locateButtonFetch();
})
async function getLongAndLat() {
    //i have tried to make that await for onSuccess result, but I don't know how
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

var onSuccess = async function (position) {
    //that array is ofc global
    localisationCords[0] = position.coords.latitude;
    localisationCords[1] = position.coords.longitude;
};

function onError(error) {
    alert('Error: ' + error.message);
}
const locateButtonFetch = async () => {
    await getLongAndLat();
    console.log(localisationCords[0] + " + " + localisationCords[1]); //this logs undefined + undefined
    link = "https://api.openweathermap.org/data/2.5/onecall?lat=" + localisationCords[0] + "&lon=" + localisationCords[1] + "&exclude=daily&appid={myOWApi key}&units=metric";
    await fetch(link)
        .then((resp) => resp.json())
        .then(function (data) {
            future = data;
            console.log(future);
        })
        .catch(function (error) {
            console.log(error);
        });
}
我确实错过了一些东西,但是我在这个论坛上找到的所有帖子都没有解决我的问题,我也没有尝试修改这些帖子。

提前感谢。

您遇到的主要问题是
getLongAndLat()
未设置为使用
Wait
。它返回一个隐式承诺(由
async
前缀引起),但不是仅在授予(或取消)位置时才解析的承诺。由于
getCurrentPosition()
不返回承诺,我们需要自己手动处理承诺

试试这个:

locate.addEventListener("click", locateButtonFetch);

function getLongAndLat() {
    return new Promise((resolve, reject) =>
        navigator.geolocation.getCurrentPosition(resolve, reject)
    );
}

const locateButtonFetch = async () => {
    try {
        let position = await getLongAndLat(),
            { coords } = position,
            url = "https://api.openweathermap.org/data/2.5/onecall?lat="+coords.latitude+"&lon="+coords.longitude+"&exclude=daily&appid={myOWApi key}&units=metric";
        await fetch(url)
            .then(resp => resp.json())
            .then(data => {
                let future = data;
                console.log(future);
            })
            .catch(e => console.log(error));
    } catch(e) {
        alert('Error: '+e.message);
    }
}

您必须在该定位中添加async await。addEventListener(“单击”,异步函数(){await locateButtonFetch();})现在可以工作了,但只有在第二次单击后,第一次单击显示的错误与您尝试此定位时的错误相同。addEventListener(“单击”,异步函数(){await locateButtonFetch();})@JayParmar是的,我做了,遗憾的是,它从第一次开始就不能工作。它工作得很好,非常感谢。那是我的主要嫌疑犯,但我不知道如何解决。我想我需要在承诺方面做更多的工作:)如果你能原谅这个插件,我有关于和的深入指南。