Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active June 1, 2019 02:34
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 harrisonmalone/396683f73abf07b262de8e553102b8fa to your computer and use it in GitHub Desktop.
Save harrisonmalone/396683f73abf07b262de8e553102b8fa to your computer and use it in GitHub Desktop.
solution for async await currency challenge, helping out student refactor some code
const axios = require('axios');
const fetch = require("node-fetch");
// Use the first API URL inside this function
async function getExchangeRate(currencyCode, amount) {
const response = await axios.get('http://apilayer.net/api/live?access_key=20180807dcc302bd6ff89174614f5795&currencies=' + currencyCode + '&source=USD&format=1');
const USD = 'USD'
const interpolateCurrency = USD + currencyCode
const apiAmount = response.data.quotes[interpolateCurrency]
const total = apiAmount * amount;
return total.toFixed(2)
}
// get just the country names
const getCountry = (response) => {
const countries = []
response.forEach((country) => {
countries.push(country.name)
})
return countries
}
// Use the second API URL inside this function
async function getCountries(currencyCode) {
const getData = await fetch(`https://restcountries.eu/rest/v2/currency/${currencyCode}`)
const response = await getData.json()
const arrayOfCountries = getCountry(response)
return arrayOfCountries
}
// Complete the function convert given the following arguments:
// Hint: Use the functions you have completed above!
async function convertCurrencyUSD(currencyCode, amount) {
const countryList = await getCountries(currencyCode)
const countryListFormatted = countryList.join(", ")
const totalFromExchange = await getExchangeRate(currencyCode, amount)
return `\$${amount} USD is worth \$${totalFromExchange} ${currencyCode} 💰\nYou can spend ${currencyCode} in the following countries: ${countryListFormatted}`
}
// log result to console inside of try and catch
async function handleResult() {
try {
const result = await convertCurrencyUSD('AUD', 20)
console.log(result)
}
catch(error) {
console.log(error.message)
}
}
handleResult()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment