Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
foundation/exercises/06_code_quality/asyncFunctions.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
53 lines (44 sloc)
1.28 KB
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
'use strict' | |
const request = require('request') | |
const readline = require('readline-sync') | |
const baseURL = 'https://api.exchangeratesapi.io/latest' | |
async function main() { | |
try { | |
const base = await getInput('enter base currency') | |
await checkValidCurrencyCode(base) | |
const data = await getData(`${baseURL}?base=${base}`) | |
await printObject(data) | |
const to = await getInput('convert to') | |
console.log(to) | |
process.exit() | |
} catch (err) { | |
console.log(`error: ${err.message}`) | |
} | |
} | |
const getInput = prompt => new Promise(resolve => { | |
const response = readline.question(`${prompt}: `) | |
return resolve(response) | |
}) | |
const checkValidCurrencyCode = code => new Promise( (resolve, reject) => { | |
code = code.trim() | |
request(baseURL, (err, res, body) => { | |
if (err) reject(new Error('invalid API call')) | |
const rates = JSON.parse(body).rates | |
if (!rates.hasOwnProperty(code)) throw new Error(`invalid currency code ${code}`) | |
resolve() | |
}) | |
}) | |
const getData = url => new Promise( (resolve, reject) => { | |
request(url, (err, res, body) => { | |
if (err) reject(new Error('invalid API call')) | |
resolve(body) | |
}) | |
}) | |
const printObject = data => new Promise( (resolve) => { | |
const indent = 2 | |
data = JSON.parse(data) | |
const str = JSON.stringify(data, null, indent) | |
console.log(str) | |
resolve() | |
}) | |
main() |