- Jan 2, 2006
- 10,455
- 35
- 91
This is the first time I've tried writing a promise and I'm not quite able to get it to work. I need to have Googlemap's geocoder take a street address and return GPS coordinates, which is an async call.
I'm using this as a tutorial:
http://www.html5rocks.com/en/tutorials/es6/promises/#toc-javascript-promises
Help?
I'm using this as a tutorial:
http://www.html5rocks.com/en/tutorials/es6/promises/#toc-javascript-promises
Code:
var geocode = new Promise(function(resolve, reject) {
// async call to Google's Geocoder - takes street address
// and returns GPS coordinates
var address = "1600 Amphitheatre Pkwy, Mountain View, CA 94043";
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log("got results!");
var gpsPosition = {};
gpsPosition.B = results[0].geometry.location['B'];
gpsPosition.k = results[0].geometry.location['k'];
console.log(gpsPosition);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
// this part just isn't working
// what should go inside this if statement to check
// if the async call worked and gpsPosition has been defined?
if (!!gpsPosition.B /* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
geocode.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
Help?
Last edited: