将 getCurrentPosition() 值推入数组但无法控制数组的日志元素

Pushing getCurrentPosition() values into array but cannot console log elements of the array

我已将地理定位 API 包装在 getLocation() 函数中并返回一个数组。但是,当我尝试访问数组的特定元素时,我变得不确定。我觉得我在这里遗漏了一些非常简单的东西。

 const getLocation = function () {
        const arrLocations = [];
        navigator.geolocation.getCurrentPosition(function (position) {
            arrLocations.push(position.coords.latitude)
            arrLocations.push(position.coords.longitude)
        });
        return arrLocations;
    }
    const coord = getLocation();
    console.log(coord);
    console.log(coord[0]);

我还尝试将地理位置包装在一个承诺中 以防万一getCurrentPosition 发生一些异步。调用 returns 未定义。 (我不确定我是否写对了承诺。我对JavaScript比较陌生):

    new Promise(function (resolve, reject) {
        const arrLocations = [];
        navigator.geolocation.getCurrentPosition(function (position) {
            arrLocations.push(position.coords.latitude)
            arrLocations.push(position.coords.longitude)
        });

        if (!arrLocations) {
            resolve(arrLocations);
        }
        else {
            reject();
        }
    })
        .then(function (arr) {
            return arr;
        })
        .catch(function (e) {
            console.log(`Something went wrong: ${e}`);
        });

为什么数组中的元素返回未定义?为什么承诺返回未定义?谢谢!

getCurrentPosition() 是异步的,这就是为什么您的第一个代码段不起作用的原因。在异步函数推送任何内容之前,您正在返回并尝试记录 arrLocations。在你的第二个想法中使用 promise 是一个很好的直觉,它只需要一点点调整。

这是一种方法。只是 resolve 你想要的数组,并利用 getCurrentPosition 的第二个参数进行错误回调以在需要时拒绝。 (您可能只会在 SO 片段中得到错误):

const getLocation = function() {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      (position) => resolve([position.coords.latitude, position.coords.longitude]),
      (error) => reject(error)
    );
  })
}

// to use it:

getLocation()
  .then(arrLocations => console.log(arrLocations))
  .catch(err => console.log("there was an error: ", err))