You could wrap your function inside a Promise and wait for it to resolve. This way you can extract the values whenever they become available using the then method. It is kind of similar to adding a callback but it works differently.
So the code below here does not execute here on SO for security reasons, but it will in your own file.
The Promise can take a callback function with 2 parameters. resolve and reject.
resolve could be seen as something like return. But instead of returning the value it stores it in the Promise and changed the state of the Promise to resolved. When that happens all adjecent then methods will be called.
reject is when an error occurs or you simply don't want the Promise to resolve. It calls the adjecent catch block after the Promise statement.
In the then and catch blocks you can access your resolved or rejected values.
Check out more examples in this Medium article.
/**
* Wrap function in a Promise.
* Resolve when position is found.
* Reject when error occurs.
*/
const getLocation = () => new Promise(
(resolve, reject) => {
window.navigator.geolocation.getCurrentPosition(
position => {
const location = {
lat:position.coords.latitude,
long:position.coords.longitude
};
resolve(location); // Resolve with location. location can now be accessed in the .then method.
},
err => reject(err) // Reject with err. err can now be accessed in the .catch method.
);
}
);
/**
* then is called when the Promise is resolved
* catch is called when the Promise rejects or encounters an error.
*/
getLocation()
.then(location => console.log(location))
.catch(error => console.log(error));