I’m trying to make a helper function to get the current location of the user, but the result of my promise is undefined.
This function is working and I can retrieve my coordinates :
//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'); } }); }
But when I call my function here, I get undefined :
import {getUserLocation} from '../../utils/position'; useEffect(() => { getUserLocation() .then((res) => console.log(res)) // { undefined } .catch((err) => { console.error(err.message); }); }, []);
What am I doing wrong?
Advertisement
Answer
As written, getUserLocation() does not return its request(…).then() promise. Change await
to return
.
Also, you should really change console.log('Location is not enabled')
to throw new Error('Location is not enabled')
, thus allowing getUserLocation’s caller to see the error (should it arise).
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. } }); }