Async and await let us handle asynchronous code easily, it's somehow similar to generators, pausing the execution whenever the await
is prefixed:
// To be able to wait for a call we need to mark a function as async
async function getTemperature () {
// We wait until the getWeather function returns the value
const weather = await getWeather(....);
// Once the value is ready the execution is resumed and we can use the result
return weather.temperature;
}
An async function can be piped like a promise
getTemperature().then(console.log);
As for Promise piping, the easiest way to handle possible errors is using the .catch
clause.
getTemperature()
.then(console.log)
.catch(console.error);