Promisifying Geolocation

The last post promisified setTimeout. This one promisifies a real browser API from all the way back in post 1, geolocation, and uses it to rebuild whereAmI without hardcoded coordinates.

July 11, 20263 min read15 / 22

The last post promisified setTimeout. This one promisifies something with actual data attached, the geolocation API from post 1, and uses it to make whereAmI finally figure out its own coordinates instead of being handed them.

Reviewing the Callback-Based API

navigator.geolocation.getCurrentPosition takes two callbacks, one for success, one for failure, the exact shape a Promise executor is built to wrap.

JavaScript
navigator.geolocation.getCurrentPosition( (position) => console.log(position), (error) => console.error(error) );

Non-blocking, same as it's always been: the browser asks for permission, works out the location in the background, and calls whichever callback fits once it's done.

Promisifying getCurrentPosition

Wrapping it looks exactly like wrapping setTimeout did.

JavaScript · Live Editor
Loading editor...

resolve and reject already match the exact shape getCurrentPosition expects, a success callback and an error callback, so they can be passed straight in as those two arguments, no wrapper function needed around either one.

The lifecycle of a Promise: pending while the task runs, then settling exactly once into either fulfilled or rejected, a state that never changes afterward. ExpandThe lifecycle of a Promise: pending while the task runs, then settling exactly once into either fulfilled or rejected, a state that never changes afterward.

Rebuilding whereAmI Without Manual Coordinates

The coding challenge took lat and lng as arguments. With getPosition in hand, the function can just ask the device directly and chain everything after it.

JavaScript · Live Editor
Loading editor...

Hit Run, allow location access when the browser asks, and the card that renders is wherever this page is actually being read from, no coordinates typed in anywhere. Six chained steps, geolocation, geocoding, country lookup, rendering, error handling, cleanup, all flat, all through the exact same .then() pattern this whole series has been building toward.

The Essentials

  1. A callback-based API with a success callback and an error callback promisifies by passing resolve and reject straight in as those two callbacks.
  2. No wrapper function is needed when the callback signatures already match what resolve/reject expect.
  3. A promisified geolocation call chains into everything else exactly like a promisified timer or a fetch call does, same .then(), same .catch(), same .finally().