You have to instantiate a new deferred object and return it (or its promise) from the function. Call its .resolve method once you get the response:
var getLocation = function() {
var deferred = new $.Deferred();
navigator.geolocation.getCurrentPosition(function( position ){
// Stuff with geolocation
deferred.resolve(position);
});
// return promise so that outside code cannot reject/resolve the deferred
return deferred.promise();
};
Usage:
getLocation().then(drawMarkerOnMap);
Reference: jQuery.Deferred
Addendum:
I would advise against using both approaches, deferred objects and passing callbacks to the function, to keep the interface simple. But if you have to stay backwards compatible, you can simply register the passed callback at the deferred object:
var getLocation = function(callback) {
var deferred = new $.Deferred();
if ($.isFunction(callback)) {
deferred.then(callback);
}
navigator.geolocation.getCurrentPosition(function( position ){
// Stuff with geolocation
deferred.resolve(position);
});
// return promise so that outside code cannot reject/resolve the deferred
return deferred.promise();
};