React Native Geolocation等待功能不起作用



我正试图从react本机包中获取地理位置">@react native community/geolocation";。单击按钮,我想获得纬度和经度,为此,我正在创建一个名为getUserCurrentLocation((的单独函数,但我想将该函数设置为异步等待类型。

const getUserCurrentLocation = () async => {
await Geolocation.getCurrentPosition(
info => {
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);  
},
error => console.log(error),
{
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 10,
distanceFilter: 0,
},
);
};

您需要将async移到括号后面。这就是如何使用异步并等待try-and-catch块

const getUserCurrentLocation = async () => {
try {
const info = await Geolocation.getCurrentPosition();
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude); 
} catch(error) {
console.log(error);
}
};

但我在Documents上看到你不需要使用promise。这是一个例子,它应该正常工作:参观https://github.com/react-native-geolocation/react-native-geolocation/blob/master/example/GeolocationExample.js#:~:text=componentDidMount((%20%7B-,Geolocation.getCurrentPosition(,(%3B,this.watchID%20%3D%20Geolocation

Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);

最新更新