One of my friends is such a sweetheart. Whenever I drop her home she's concerned about me especially because she knows how I drive so she asks me to promise her that I'll let her know when I reach my home. Sometimes I do, sometimes I forget, and sometimes she calls me to ask.
She came to my mind while I was playing today with jQuery's deferred and JavaScript 6 promises with the GeoLocation API, i.e. navigator.geolocation.getCurrentPosition(successcalback, failcallback, options);
Promises is a standard part of EcmaScript 6 and is natively supported in modern browsers. It is an alternate way to handling asynchronocity prevalent in modern web applications and much cleaner than callbacks in certain situations. Callbacks are better suited in other asynchronous situations (for example a UI event).
Just to try promises out (native and jQuery's deferred), I'll ask the user for their location as a promise. I might get the location, a declination, or I will wait forever (until the browser's page is closed).
The only native geolocation API relies on callbacks as you can see from the signature above with the success and failure callback parameters. To use promises, I'm going to use a jQuery deferred object (an object that is eventually resolved), and abstract the geolocation API with a function that returns a promise of the geolocation (or a declination, and otherwise we'll just wait forever). The function locationPromise below does so.
If you often ask the user for their location using getCurrentPosition, you might want to use a promise-styled API just like the one below.
function locationPromise() {
var def = $.Deferred();
var gotLocation = function (geopos) {
def.resolveWith(geopos);
}
var notLocation = function () {
def.rejectWith("Wonder where you are!");
}
window.navigator.geolocation.getCurrentPosition(gotLocation, notLocation, {});
var myPromise = def.promise();
return myPromise;
}
We use this function as follows:
function getLocationPromise() {
locationPromise()
.done(function () {
//this will be the value resolved or rejected
console.log(this.coords);
})
.fail(function () { alert("sorry weren't able to get pos"); });
}
The usefulness of this depends on the architecture of your application. You base your architecture on common functionality that handles promises with metadata (for example as how to respond to success or failure) instead of callbacks. So this examples shows how you can convert an asynchronous HTML5 operation (geolocation) to a promise.