【发布时间】:2021-01-11 11:00:57
【问题描述】:
我正在尝试制作一个辅助函数来获取用户的当前位置,但我的承诺的结果是未定义的。
此功能正在运行,我可以检索我的坐标:
//position.js
async function getCurrentPosition() {
return new Promise((resolve, reject) => {
Geolocation.getCurrentPosition(resolve, reject, {
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
});
});
}
export async function getUserLocation() {
await request(
// Check for permissions
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
}),
).then((res) => {
console.log('then');
// Permission OK
if (res === 'granted') {
console.log('granted');
return getCurrentPosition();
// Permission denied
} else {
console.log('Location is not enabled');
}
});
}
但是当我在这里调用我的函数时,我得到了 undefined :
import {getUserLocation} from '../../utils/position';
useEffect(() => {
getUserLocation()
.then((res) => console.log(res)) // { undefined }
.catch((err) => {
console.error(err.message);
});
}, []);
我做错了什么?
【问题讨论】:
-
先尝试使用字符串,例如“Resolved”和“Rejected”,还将您的 Geolocation.getCurrentPosition 添加到 try and catch 块中
-
我试过你说的但仍然有未定义,即使我尝试传递字符串而不是 position.coords
-
你用什么平台?真机还是模拟器?因为您的代码与我的 android 模拟器一起工作并返回了一个位置。
-
IOS 模拟器。但是我也可以在 getCurrentPosition() 函数中获得一个位置,但是当我在我的使用效果中(在另一个文件中)调用它时,我无法获得解析值。那里:.then((res) => console.log(res)) // { undefined }
-
如所写,
getUserLocation()不会返回其request(...).then()承诺。将await更改为return。
标签: javascript react-native promise geolocation