4.9 Abstracting Callbacks

Refactoring app.js. Taking complex logic code to a separate file.

Create a new directory and file both called geocode.

Leave only geocode.geocodeAddress(argv.address); at app.js.

In geocode.js, we add the following code

const request = require('request');
var geocodeAddress = (address) => {
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}`,
json: true // convert string to Json for you
}, (err, res, body)=> {
if (err) { // err object only checks machine errors
console.log("Unable to connect to Google Servers!");
} else if (body.status === 'ZERO_RESULTS') { // when address not found
console.log("Unable to find that address.")
} else if (body.status === 'OK') {
console.log(`Address: ${body.results[0].formatted_address}`);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longtitude: ${body.results[0].geometry.location.lng}`);
}
})
}
module.exports = {
geocodeAddress
}

More Abstraction

geocode.geocodeAddress(argv.address, (errorMessage, results)=> {
if (errorMessage) console.log(errorMessage);
else console.log(JSON.stringify(results, undefined, 2));
}); // only one of these is gonna have at one time
var geocodeAddress = (address, callback) => {
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}`,
json: true // convert string to Json for you
}, (err, res, body)=> {
if (err) { // err object only checks machine errors
callback("Unable to connect to Google Servers!");
} else if (body.status === 'ZERO_RESULTS') { // when address not found
callback("Unable to find that address.")
} else if (body.status === 'OK') {
callback(undefined, {
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longtitude: body.results[0].geometry.location.lng
});
}
})
}