JSFiddle - React, Tailwind, and code Playground

by Russ Bain

HTML

<p>
  Note: to get the Geolocation API to work,
  you may need to enable it in Chrome devTools. 
  
  Open the console, hit the 'esc' key, click on the the three dot menu,
  choose 'sensors', then choose a location from the
  drop down menu
  
</p>

JavaScript

/**
 * Wrap function in a Promise.
 * Resolve when position is found.
 * Reject when error occurs.
 */
 
  var foo = 'flabarthagon';
  
  var someFn = function(cb){
    console.log('About to call the callback')
    return cb('callback - FIRST\n foo:', foo);
  };
  
  var callback = function(message){
    console.log(message, foo);
  };
  
    
  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) => {
      if (foo !== undefined){
      foo = location;
    }
    console.log('THEN\n - Sometimes third, sometimes fourth!\n foo:', foo)
  })
  .catch(error => console.log(error));

// at near zero delay, this sometimes goes after the Promise. When it gets executed determines whet

setTimeout(function(){
  console.log('SetTimeout\n -  Foo only changes if this goes AFTER the Promise\n foo:', foo)}
  , 0);
  
 

someFn(callback);
console.log('OUTSIDE - SECOND\n foo:', foo)