4.11 Chaining Callbacks Together

Refactor Forecast part.

weather.getWeather();
const request = require('request');
var getWeather = () => {
request({
url: "https://api.darksky.net/forecast/a4fdda5fd0d59408f5addb4bd022a199/37.09024,-95.712891",
json: true
}, (err, res, body)=> {
if (err) {
console.log("unable to connect to Forecast.io Server.");
} else if (body.code === 400) {
console.log(body.error);
} else {
console.log(body.currently.temperature);
}
});
};
module.exports.getWeather = getWeather;

Abstract More

weather.getWeather(37.09024, -95.712891, (weatherErr, weatherResult) => {
if (weatherErr) console.log(weatherErr);
else console.log(JSON.stringify(weatherResult, undefined, 2));
});
var getWeather = (lat, lng, callback) => {
request({
url: `https://api.darksky.net/forecast/a4fdda5fd0d59408f5addb4bd022a199/${lat},${lng}`,
json: true
}, (err, res, body)=> {
if (err) {
callback("unable to connect to Forecast.io Server.");
} else if (body.code === 400) {
callback(body.error);
} else {
callback(undefined, {
temperature: body.currently.temperature,
apparentTemperature: body.currently.apparentTemperature
});
}
});
};

Chaining Callbacks

geocode.geocodeAddress(argv.address, (geoErr, geoResult) => {
if (geoErr) console.log(geoErr);
else {
console.log(geoResult.address)
weather.getWeather(geoResult.latitude, geoResult.longitude, (weatherErr, weatherResult) => {
if (weatherErr) console.log(weatherErr);
else console.log(`It's currently ${weatherResult.temperature}. It feels like ${weatherResult.apparentTemperature}.`);
});
}
});