Promises aim to solve a lot of the problems that come up when we have a lot of asynchronous code in our application. They make it a lot easier to manage our asynchronous computations—things such as requesting data from a database. Alternatively, in the case of a weather app, things such as fetching data from a URL.
In the app.js file we do a similar thing using callbacks:
const yargs = require('yargs');
const geocode = require('./geocode/geocode');
const weather = require('./weather/weather');
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
describe: 'Address to fetch weather for',
string: true
}
})
.help()
.alias('help', 'h')
.argv;
geocode.geocodeAddress(argv.address, (errorMessage, results) => {
if (errorMessage) {
console.log(errorMessage);
} else {
console.log(results.address);
weather.getWeather(results.latitude, results.longitude, (errorMessage, weatherResults) => {
if (errorMessage) {
console.log(errorMessage);
} else {
console.log(`It's currently ${weatherResults.temperature}. It feels like ${weatherResults.apparentTemperature}.`);
}
});
}
});
In this code, we have two callbacks:
- One that gets passed into geocodeAddress
- One that gets passed into getWeather
We use this to manage our asynchronous actions. In our case, it's things such as fetching data from an API, using an HTTP request. We can use promises in this example to make the code a lot nicer. This is exactly the aim later in the chapter.
In this section, we'll explore the basics concept of promises. We'll compare and contrast callbacks with promises just yet, because there's a lot more subtleties than can be described without knowing exactly how promises work. So, before we talk about why they're better, we will simply create some.