【问题标题】:Updating values in async await在异步等待中更新值
【发布时间】:2018-10-25 02:42:32
【问题描述】:

我开发了一小段代码,它可以获取当前的纬度和经度,并将它们传递给 Google 地图 URL 以获取地图数据。

lat 和 lon 变量最初设置为 undefined,然后在调用 navigator.geolocation.getCurrentPosition 时更新它们的值。此函数确实通过位置对象正确返回数据。但是不知何故,变量的值没有更新,并且在传递到 URL 时仍然未定义。

问题出在哪里?

const getLocationDetails = async () => {

    let lat = undefined;
    let lon = undefined;

    await navigator.geolocation.getCurrentPosition( position => {
        lat = position.coords.latitude;
        lon = position.coords.longitude;
    });
    const res = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}`,
        { method: 'GET' });
    const response = await res.json();

};

【问题讨论】:

  • position.coords.latitude 这是已经存在还是需要一些时间才能填充?只需创建一个新的异步函数,它将返回值。并在定义 let lat = asynfunction(); 时使用它

标签: javascript async-await


【解决方案1】:

getCurrentPosition 不返回承诺,因此await 在那里是空操作,并且函数不会暂停等待操作getCurrentPosition 开始完成。当您await 不是承诺时,执行会立即继续。

相反,给自己一个启用承诺的版本:

const asyncGetCurrentPosition = options => new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, options);
});

然后使用它:

const getLocationDetails = async () => {
    let {coords: {latitude, longitude}} = await asyncGetCurrentPosition();
    const res = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}`,
        { method: 'GET' });
    // Note: Missing a `res.ok` check here
    const response = await res.json();
};

(其中的let {coords: {latitude, longitude}} = .. 部分是解构赋值,将coords.latitudecoords.longitude 分别放入latitudelongitude 变量中。然后我更新了fetch 使用latitudelongitude [而不是latlon]。也可以在这里使用const,因为你不改变latitudelongitude。风格问题。 )

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2014-09-06
    • 1970-01-01
    • 2023-03-12
    • 2019-08-31
    • 2020-02-01
    相关资源
    最近更新 更多