Skip to content

Instantly share code, notes, and snippets.

@bflannery
Created January 18, 2019 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bflannery/4ba0be5e30a3defdf66ac6d873f51e3d to your computer and use it in GitHub Desktop.
Save bflannery/4ba0be5e30a3defdf66ac6d873f51e3d to your computer and use it in GitHub Desktop.
Async Currency Converter
const getExchangeRate = async (from, to) => {
try {
const apiKey = '' // Add unique fixer.io apiKey
const response = await axios.get(`http://data.fixer.io/api/latest?access_key=${apiKey}&format=1`)
const euro = 1 / response.data.rates[from];
const rate = euro * response.data.rates[to];
if (isNaN(rate)) {
throw new Error()
}
} 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 convertedAmount = (amount * rate).toFixed(2);
const countries = await getCountries(to)
return `${amount} ${from} is worth ${convertedAmount} ${to}. You can spend these 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