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 :
JavaScript
x
32
32
1
//position.js
2
3
async function getCurrentPosition() {
4
return new Promise((resolve, reject) => {
5
Geolocation.getCurrentPosition(resolve, reject, {
6
enableHighAccuracy: true,
7
timeout: 15000,
8
maximumAge: 10000,
9
});
10
});
11
}
12
13
export async function getUserLocation() {
14
await request(
15
// Check for permissions
16
Platform.select({
17
android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
18
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
19
}),
20
).then((res) => {
21
console.log('then');
22
// Permission OK
23
if (res === 'granted') {
24
console.log('granted');
25
return getCurrentPosition();
26
// Permission denied
27
} else {
28
console.log('Location is not enabled');
29
}
30
});
31
}
32
But when I call my function here, I get undefined :
JavaScript
1
10
10
1
import {getUserLocation} from '../../utils/position';
2
3
useEffect(() => {
4
getUserLocation()
5
.then((res) => console.log(res)) // { undefined }
6
.catch((err) => {
7
console.error(err.message);
8
});
9
}, []);
10
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).
JavaScript
1
17
17
1
export async function getUserLocation() {
2
return request(Platform.select({ // Check for permissions
3
// ^^^^^^
4
'android': PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
5
'ios': PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
6
}))
7
.then((res) => {
8
if (res === 'granted') { // Permission OK
9
return getCurrentPosition();
10
} else { // Permission denied
11
throw new Error('Location is not enabled'); // Throwing an Error here
12
// makes it available to the caller
13
// in its catch clause.
14
}
15
});
16
}
17