Hi,
I try to create a class for geoLocation, but as I see the HTML5 geolocation works asyncronous.
My question: is there any way to create asyncron class?
my atempt
"use strict";
class Location {
constructor() {
this.coordinates = {
long: null,
lat: null
};
this.time = null;
this.error = null;
};
get long() {
return this.coordinates.long;
}
get lat() {
return this.coordinates.lat;
}
}
// create the myLocation class:
const getLocation = () => {
return new Promise(waitForLocation => {
const myLocation = new Location();
const showPosition = (position) => {
myLocation.coordinates.lat = position.coords.latitude;
myLocation.coordinates.long = position.coords.longitude;
myLocation.time = position.timestamp;
waitForLocation(myLocation);
};
const showError = error => {
myLocation.error = error;
waitForLocation(myLocation);
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
myLocation.error = "Geolocation is not supported by this browser.";
waitForLocation(myLocation);
}
});
};
// get location:
const myLocation = getLocation();
console.log(myLocation); // Promise {<pending>}
myLocation.then(myLocation => {
console.log(myLocation);
console.log(myLocation.long);
console.log(myLocation.lat);
});
now I need to use the myLocation.then() method but I try to find any way to use after creation simple:
myLocation.long;
myLocation.lat… etc. without to use callback (then(callback => {…my code goes here}));
How to modify the getLocation() to return me not a pending class?