setTimeout(() => { console.log('This runs after 1000 milliseconds.'); }, 1000);
asyncCallOne(() => { asyncCallTwo(() => { asyncCallThree(() => { asyncCallFour(() => { asyncCallFive(() => { //выполнение неких действий }) }) }) }) })
const promiseFunction = new Promise((resolve, reject) => { const add = (a, b) => a + b; resolve(add(2, 2)); }); promiseFunction.then((response) => { console.log(response); }).catch((error) => { console.log(error); });
promiseFunction()
function of this example returns a Promise
object, which is some kind of action performed by the function. A call to the resolve()
method indicates that its work has been successfully completed. In similar constructions, the .then()
promis method is also used - with its help, after successfully resolving the promise, you can perform a kind of callback. The .catch()
method is called in cases when something went wrong during the work of the promise.async
(asynchronous functions) enable us to write neat and not overloaded with service structures code that allows us to get the same result that we obtained using promises. It should be noted that the async
is, in essence, only “syntactic sugar” for promis.async
keyword when declaring a function. It looks like this: const asyncFunction = async () => { // Код }
await
keyword. It can only be used in asynchronous functions. It allows you to return the result of the asynchronous function, which will be available after such a function completes the execution of a certain task. // Асинхронная функция const asyncGreeting = async () => 'Greetings'; // Промис const promiseGreeting = () => new Promise(((resolve) => { resolve('Greetings'); })); asyncGreeting().then(result => console.log(result)); promiseGreeting().then(result => console.log(result));
async
allows you to write asynchronous code that looks like synchronous. This code is much easier to work with.npm init
command in it. When the program asks us a question about the name of the package being created, enter currency-converter
. The remaining questions of the program can not be answered by pressing Enter
in response. After that, install the Axios package in our project by running the command npm install axios --save
in its directory. Create a new file named currency-converter.js
. const axios = require('axios');
getExchangeRate()
, which will take two arguments: fromCurrency
and toCurrency
: const getExchangeRate = async (fromCurrency, toCurrency) => {}
const response = await axios.get('http://www.apilayer.net/api/live?access_key=[ваш код доступа к API]');
response
object at the address response.data.quotes
. Here is what a fragment of an object looks like with data of interest to us (it is visible in the program as response.data
): { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1547891348, "source":"USD", "quotes":{ "USDAED":3.673042, "USDAFN":75.350404, "USDALL":109.203989, ... "USDZWL":322.355011 } }
rate
constant: const rate = response.data.quotes;
response.data.source
. Write the base currency code in the baseCurrency
constant: const baseCurrency = response.data.source;
usd
into which we write the result of dividing 1 by the currency rate in which the amount is given: const usd = 1 / rate[`${baseCurrency}${fromCurrency}`];
USD
and ending with the code of the corresponding currency. Since it is assumed that our program accepts string currency codes, we generate a key by concatenating a string containing the code of the base currency and what is passed to the function in the fromCurrency
parameter.fromCurrency
to the currency toCurrence
, we multiply the constant usd
by the rate for toCurrency
. It looks like this: const exchangeRate = usd * rate[`${baseCurrency}${toCurrency}`];
exchangeRate
returned from the function. Here is what its full code looks like: const getExchangeRate = async (fromCurrency, toCurrency) => { try { const response = await axios.get('http://www.apilayer.net/api/live?access_key=[ваш код доступа к API]'); const rate = response.data.quotes; const baseCurrency = response.data.source; const usd = 1 / rate[`${baseCurrency}${fromCurrency}`]; const exchangeRate = usd * rate[`${baseCurrency}${toCurrency}`]; return exchangeRate; } catch (error) { throw new Error(`Unable to get currency ${fromCurrency} and ${toCurrency}`); } };
getCountries()
, which asynchronously loads information about countries in which you can use the currency into which we convert the amount specified in another currency, will take the argument currencyCode
: const getCountries = async (currencyCode) => {}
const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
HRK
(Croatian Kuna) code in the request, then in response we will receive a JSON-code, a fragment of which is shown below: [ { "name":"Croatia", ... } ]
name
these objects contain the name of the country. You can access this array using the response.data
construction. Apply the map()
array method to extract the names of countries from the received data and return the data from the getCountries()
function, which will be an array of names of countries: return response.data.map(country => country.name);
getCountries()
function: 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 (error) { throw new Error(`Unable to get countries that use ${currencyCode}`); } };
convertCurrency ()
, will take arguments fromCurrency
, toCurrency
and amount
- currency codes and an amount. const convertCurrency = async (fromCurrency, toCurrency, amount) => {}
const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);
const countries = await getCountries(toCurrency);
const convertedAmount = (amount * exchangeRate).toFixed(2);
return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;
const convertCurrency = async (fromCurrency, toCurrency, amount) => { const exchangeRate = await getExchangeRate(fromCurrency, toCurrency); const countries = await getCountries(toCurrency); const convertedAmount = (amount * exchangeRate).toFixed(2); return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`; };
convertCurrency()
function, passing it the necessary data: convertCurrency('EUR', 'HRK', 20) .then((message) => { console.log(message); }).catch((error) => { console.log(error.message); });
node currency-converter.js
const axios = require('axios'); const getExchangeRate = async (fromCurrency, toCurrency) => { try { const response = await axios.get('http://www.apilayer.net/api/live?access_key=[ваш код доступа к API]'); const rate = response.data.quotes; const baseCurrency = response.data.source; const usd = 1 / rate[`${baseCurrency}${fromCurrency}`]; const exchangeRate = usd * rate[`${baseCurrency}${toCurrency}`]; return exchangeRate; } catch (error) { throw new Error(`Unable to get currency ${fromCurrency} and ${toCurrency}`); } }; 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 (error) { throw new Error(`Unable to get countries that use ${currencyCode}`); } }; const convertCurrency = async (fromCurrency, toCurrency, amount) => { const exchangeRate = await getExchangeRate(fromCurrency, toCurrency); const countries = await getCountries(toCurrency); const convertedAmount = (amount * exchangeRate).toFixed(2); return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`; }; convertCurrency('EUR', 'HRK', 20) .then((message) => { console.log(message); }).catch((error) => { console.log(error.message); });
Source: https://habr.com/ru/post/436884/