How to create async Class?

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?

Do you know how async/await works?

I read some example like this but I need to call then() method even with async/await syntax… I did not find the solution…
As I now the async/await are only another way (another syntax) to write asyncron function … nothing more.

Need help to import News API with axios on React

1 Like