Created
January 18, 2019 20:05
-
-
Save bflannery/4ba0be5e30a3defdf66ac6d873f51e3d to your computer and use it in GitHub Desktop.
Async Currency Converter
This file contains 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 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