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.
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.
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.
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.
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.
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
- A callback-based API with a success callback and an error callback promisifies by passing
resolveandrejectstraight in as those two callbacks. - No wrapper function is needed when the callback signatures already match what
resolve/rejectexpect. - A promisified geolocation call chains into everything else exactly like a promisified timer or a
fetchcall does, same.then(), same.catch(), same.finally().
Keep reading