Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const API_EXCHANGE = {
- host: 'openexchangerates.org',
- path: 'api/latest.json?app_id=',
- key: '1f43ea96b1e343fe94333dd2b97a109d',
- };
- const DEFAULT_RETRY = 3;
- const promiseRetry = async (promiseFactory, retry = DEFAULT_RETRY) => {
- console.log({ retry });
- const promise = promiseFactory();
- try {
- const res = await promise;
- return res;
- }
- catch {
- const attemptsLeft = retry - 1;
- if (attemptsLeft > 0)
- return promiseRetry(promiseFactory, attemptsLeft);
- throw new Error('Can not get data');
- }
- }
- const tryFetch = async (url, options) => {
- const resp = await fetch(url, options);
- if (!resp.ok)
- throw new Error('ok is false');
- return await resp.json();
- }
- const getRate = async (currency) => {
- // console.log({ currency, retry });
- const { host, path, key } = API_EXCHANGE;
- const url = `https://${host}/${path}${key}`;
- const data = await tryFetch(url);
- const rate = data.rates[currency];
- return rate;
- };
- const getTime = async () => {
- const url = 'http://worldtimeapi.org/api/timezone/Europe/Kyiv';
- const data = await tryFetch(url);
- const { datetime } = data;
- return new Date(datetime);
- }
- const main = async () => {
- try {
- const rate = await promiseRetry(() => getRate('UAH'));
- console.log({ rate });
- // const time = await promiseRetry(() => getTime());
- // console.log({ time });
- } catch (err) {
- console.error({ err });
- }
- };
- main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement