I would like to call the Google Maps Geocoding API using a Promise like this:
function makeGeoCodingRequest(address,bounds)
{
/*
Input parameters
If you depend on a promise in order to return your data, you must return a promise from your function.
Once 1 function in your callstack is async, all functions that want to call it have to be async as well if you want to continue linear execution. ( async = return a promise )
Notice that your if
statement does not have braces and thus only the first statement after it will not be executed if the condition fails.
I fixed it in this example. Notice the remarks I added.
if(address){
promise=Q($.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=API_KEY"
}));
return promise.then(function(data) {
// whatever you return here will also become the resolve value of the promise returned by makeGeoCodingRequest
// If you don't want to validate the data, you can in fact just return the promise variable directly
// you probably want to return a rejected promise here if status is not what you expected
if (data.status === "OK") return data;
else console.error(messages[data.status]);
return null;
});
}
You must call makeGeoCodingRequest
in the following fashion.
makeGeoCodingRequest(address,bounds).then(function(data){
// this will contain whatever
console.log(data);
});