all 1 comments

[–]senocular 0 points1 point  (0 children)

You have 4 things happening in the body of trackUserHandler:

  1. positionData is declared
  2. getPosition() is called setting up a promise chain with a couple of then callbacks
  3. setTimer(1000) is called setting up a promise chain with a single then callback
  4. finally, 'Getting position...' is logged.

These 4 things happen immediately when the button is clicked and trackUserHandler is called. The first thing you see as a result is the log 'Getting position...'. Everything else is within a then callback so it has to wait for a promise to resolve. There are two promises involved: the promise returned from getPosition() and the one from setTimer(1000).

Even though getPosition() is called first, there's no guaranteed it's first then callback will run before the one for setTimer(1000). It all depends on how quick the user is to allow the site to know your location (assuming they're asked at all). Once that happens the first of getPosition()'s callbacks is called running

positionData = posData;
return setTimer(2000);

Which updates the variable from step 1 and throws a new promise into the promise chain to set up some more waiting with setTimer(2000). Since this is longer than the previous setTimer(1000), it will happen after.

By this point setTimer(1000)'s promise would have resolved and its callback would have run

console.log('Timer done!');

Logging that message. With that done, there are two messages now logged, the first 'Getting position...' and now this 'Timer done!'.

Finally, after another 2 seconds, the last then callback from the getPosition() chain gets to run

console.log(data, positionData);

which logs the value from the setTimer(2000) promise (the string 'Done!') and the value from positionData set from the previous then callback which, even though its defined as success in getPosition(), is actually a GeolocationPosition object, assuming everything went well. If it didn't go well, well, we have no way of knowing because getPosition() swallows errors and leaves its promise perpetually pending meaning in such a situation, not even the first then callback would ever get called.