while practicing Promises
, I ended up with a simple weather application which works on the command line. I would highly appreciate it if you can point out any flaws in my code. They can be related to the efficiency, etc. I'm looking for anything you can provide in the review.
package.json
:
{
"name": "weather-app",
"version": "1.0.0",
"description": "A simple weather app.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Hassan Althaf",
"license": "MIT",
"dependencies": {
"request": "^2.67.0",
"yargs": "^3.30.0"
}
}
app.js
:
var weather = require('./weather.js');
var location = require('./location.js');
var argv = require('yargs')
.options({
location: {
demand: false,
alias: 'l',
type: 'string',
description: 'Enables you to specify a location.'
}
})
.help('help')
.argv;
if(argv.location) {
weather(argv.location).then( function(message) {
console.log(message);
}).catch( function(error) {
console.log(error);
});
} else {
location().then( function (location) {
return weather(location);
}).then( function(output) {
console.log(output);
}).catch ( function(error) {
console.log(error);
});
}
location.js
:
var url = 'http://ipinfo.io';
var request = require('request');
module.exports = function() {
return new Promise( function(resolve, reject) {
request({
url: url,
json: true
}, function (error, response, body) {
if (error || !body) {
reject('Failed to fetch the location.');
}
resolve(body.city);
});
});
};
weather.js
:
var request = require('request');
module.exports = function (location) {
return new Promise( function(resolve, reject) {
location = encodeURIComponent(location);
if(!location) {
reject('No location provided!');
}
var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&units=metric&appid=2de143494c0b295cca9337e1e96b00e0';
request({
url: url,
json: true
}, function (error, response, body) {
if(error) {
reject('Failed to fetch the weather!');
}
resolve('It\'s ' + body.main.temp + ' degrees Celsius in ' + body.name + '!');
});
});
};