将getCurrentPosition()值推入数组,但不能控制台数组的日志元素



我已经将地理位置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]);

我还尝试将地理位置封装在promise中,以防getCurrentPosition发生异步。调用返回undefined。(我不确定我是否写对了承诺。我对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。在你的第二个想法中使用承诺是一种很好的直觉,它只需要一点调整。

有一种方法。只需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))

最新更新