In the browser world you live in now, how you create your own promise unfortunately depends upon which promise library you are using. Here are a couple ways you could create a geocode(address)
function that returns its result via a promise:
// jQuery promises
function geocode(address) {
var geocoder = new google.maps.Geocoder();
var def = $.Deferred();
geocoder.geocode({ 'address': value }, function (results, status) { // called asynchronously
if (status == google.maps.GeocoderStatus.OK) {
def.resolve(results);
} else {
def.reject(status);
}
});
return def.promise();
}
// ES6 style (supported by many polyfills, promise libraries and some browsers natively)
// my favorite library is Bluebird which this would work with
function geocode(address) {
var geocoder = new google.maps.Geocoder();
return new Promise(function(resolve, reject) {
geocoder.geocode({ 'address': value }, function (results, status) { // called asynchronously
if (status == google.maps.GeocoderStatus.OK) {
resolve(results);
} else {
reject(status);
}
});
});
}
Both can be used like this which is nice and simple:
geocode(address).then(function(result) {
// code here that can use the result
}, function(errStatus) {
// code here to handle an error
});
Note: you can't take an asynchronous operation like this and make it into a synchronous operation. You just can't do that in Javascript. So, you have to learn how to program with asynchronous operations and promises are one convenient way of doing that.
Other references:
Wrap Google map geocoder.geocode in a Promise
Promises in the Google APIs JavaScript Client Library
How do I convert an existing callback API to promises?