How to use Async Wait with HTML5 GeoLocation API?
The code below show similar issue. Try to refactor it. Remember to use it with await
in async
function. Something like:
window.onload = async () => {
const getCoords = async () => {
const pos = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
return {
long: pos.coords.longitude,
lat: pos.coords.latitude,
};
};
const coords = await getCoords();
}
There are several problems with the shown snippets
getAddress()
doesn't actuallyreturn
anything.If
await
is used,then()
is not needed or vice-versa (blocking or non-blocking, not both).
Here is a correct version
async getAddress() {
// notice, no then(), cause await would block and
// wait for the resolved result
const position = await this.getCoordinates();
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let url = Constants.OSMAP_URL + latitude + "&lon=" + longitude;
// Actually return a value
return this.reverseGeoCode(url);
}
You'll also have to rewrite reverseGeoCode
in a similar fashion, something like
async reverseGeoCode(url) {
let requestService = new RequestService("json", url);
return await requestService.call();
}