Created
July 19, 2018 09:45
-
-
Save antoniojps/03c0a5137144e1dc2d29191413b7fd97 to your computer and use it in GitHub Desktop.
async await & error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const axios = require('axios'); | |
| const getExchangeRate = async (from, to) => { | |
| try { | |
| const response = await axios.get('http://data.fixer.io/api/latest?access_key=d32d75de5146611ae7f23de0782ac09b'); | |
| const euro = 1 / response.data.rates[from]; | |
| const rate = euro * response.data.rates[to]; | |
| if (isNaN(rate)) { | |
| throw new Error(); | |
| } | |
| return rate; | |
| } catch (e) { | |
| throw new Error(`Unable to get exchange rate for ${from} and ${to}.`); | |
| } | |
| }; | |
| const getCountries = async (currencyCode) => { | |
| try { | |
| const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`); | |
| return response.data.map((country) => country.name); | |
| } catch (e) { | |
| throw new Error(`Unable to get countries that use ${currencyCode}.`) | |
| } | |
| }; | |
| const convertCurrency = async (from, to, amount) => { | |
| const rate = await getExchangeRate(from, to); | |
| const countries = await getCountries(to); | |
| const convertedAmount = (amount * rate).toFixed(2); | |
| return `${amount} ${from} is worth ${convertedAmount} ${to}. You can spend it in the following countries: ${countries.join(', ')}`; | |
| }; | |
| convertCurrency('USD', 'CAD', 20).then((message) => { | |
| console.log(message); | |
| }).catch((e) => { | |
| console.log(e.message); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment