从异步函数react-native获取未定义
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从异步函数react-native获取未定义相关的知识,希望对你有一定的参考价值。
我有一系列异步函数,这些函数必须返回true或false,但是我从一个函数中得到的未定义比获得位置要多。
这里是返回未定义的函数:
async getGeoLoc(trigger = 'cDidMount') {
return navigator.geolocation.getCurrentPosition(
async position => {
const isDataReady = await this.setCityFromCoordinate(
trigger,
position.coords.latitude,
position.coords.longitude,
);
console.log('isDataReady getGeoLoc', isDataReady); // this gives true in console
return isDataReady
},
我在这里称呼它:
async getLocationPermission(trigger) {
if (Platform.OS == 'android') {
const response = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (
response == PermissionsAndroid.RESULTS.DENIED ||
response == PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN
) {
Alert.alert(
i18n.t('search:geolocation_disabled'),
i18n.t('search:need_location'),
);
return false;
} else {
return await this.getGeoLoc(trigger);
}
} else {
return await this.getGeoLoc(trigger);
// for ios go directly here
}
},
谢谢!
答案
将导航呼叫置于Promise中
function getGeoLoc(trigger = 'cDidMount') {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
async position => {
const isDataReady = await this.setCityFromCoordinate(
trigger,
position.coords.latitude,
position.coords.longitude,
);
console.log('isDataReady getGeoLoc', isDataReady); // this gives true in console
return isDataReady
},
另一答案
getCurrentPosition使用回调。如果您想使用一个单独的功能来接收头寸,则可以创建一个Promise像这样>
const myCoord = () => new Promise((resolve, reject) => { const geoSuccess = position => resolve(position); const geoFailure = error => reject(error); navigator.geolocation.getCurrentPosition( geoSuccess, geoFailure, geoOptions ); const geoOptions = { timeout: 5000, maximumAge: 5000, enableHighAccuracy: false }; });
然后您可以通过异步/等待方式调用它:
const getLocation = async () => {
const response = await myCoord();
console.log(response);
};
getLocation();
以上是关于从异步函数react-native获取未定义的主要内容,如果未能解决你的问题,请参考以下文章