udemy-node-weather-app/playground/promise2.js

30 lines
953 B
JavaScript
Raw Permalink Normal View History

2017-11-21 15:11:35 +00:00
const request = require('request')
var geocodeAddress = (address) => {
return new Promise((resolve, reject) => {
var encodedAddress = encodeURIComponent(address);
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json: true
}, (error, response, body) => {
if (error) {
reject("Unable to connect to Google Servers.");
} else if (body.status === "ZERO_RESULTS"){
reject("Unable to find that Address.");
} else if (body.status === "OK"){
resolve({
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
});
}
});
})
};
geocodeAddress(19146).then((location) => {
console.log(JSON.stringify(location, null, 2));
}, (errorMessage) => {
console.log(errorMessage);
})