Javascript 使用react-native with react-native地理位置服务中的Promise从另一个文件获取位置

Javascript 使用react-native with react-native地理位置服务中的Promise从另一个文件获取位置,javascript,react-native,promise,geolocation,Javascript,React Native,Promise,Geolocation,我试图创建一个helper函数来获取用户的当前位置,但是我的承诺的结果是未定义的 此功能正在运行,我可以检索我的坐标: //position.js async function getCurrentPosition() { return new Promise((resolve, reject) => { Geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy: true,

我试图创建一个helper函数来获取用户的当前位置,但是我的承诺的结果是未定义的

此功能正在运行,我可以检索我的坐标:

//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');
    }
  });
}
但是当我在这里调用我的函数时,我没有定义:

import {getUserLocation} from '../../utils/position';

useEffect(() => {
    getUserLocation()
      .then((res) => console.log(res)) // { undefined }
      .catch((err) => {
        console.error(err.message);
      });
  }, []);

我做错了什么?

如前所述,getUserLocation()不返回其请求(…)。然后()承诺。将
wait
更改为
return

另外,您应该将
console.log('Location is not enabled')
更改为
throw new Error('Location is not enabled')
,从而允许getUserLocation的调用者看到错误(如果出现)


首先尝试使用字符串,如“已解析”和“已拒绝”,还可以在Try and catch block中添加您的地理位置。getCurrentPosition我尝试了您所说的内容,但仍然没有定义,即使我尝试传递字符串而不是position。Coords您使用的是什么平台?以及真实的设备或模拟器?因为您的代码与我的android模拟器一起工作,并返回location.IOS模拟器。但是我也可以在getCurrentPosition()函数中获得一个位置,但是当我在use effect(另一个文件)中调用它时,我无法获得解析值。那里:.then((res)=>console.log(res))/{undefined}正如所写,
getUserLocation()
不会返回其
请求(…)。then()
promise。将
wait
更改为
return
export async function getUserLocation() {
    return request(Platform.select({ // Check for permissions
 // ^^^^^^
        'android': PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        'ios': PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
    }))
    .then((res) => {
        if (res === 'granted') { // Permission OK
            return getCurrentPosition();
        } else { // Permission denied
            throw new Error('Location is not enabled'); // Throwing an Error here
                                                        // makes it available to the caller
                                                        // in its catch clause.
        }
    });
}