Advertisement
moskalenco_a

Async refactor

May 21st, 2024
697
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const API_EXCHANGE = {
  4.   host: 'openexchangerates.org',
  5.   path: 'api/latest.json?app_id=',
  6.   key: '1f43ea96b1e343fe94333dd2b97a109d',
  7. };
  8.  
  9. const DEFAULT_RETRY = 3;
  10.  
  11. const promiseRetry = async (promiseFactory, retry = DEFAULT_RETRY) => {
  12.   console.log({ retry });
  13.   const promise = promiseFactory();
  14.   try {
  15.     const res = await promise;
  16.     return res;
  17.   }
  18.   catch {
  19.     const attemptsLeft = retry - 1;
  20.     if (attemptsLeft > 0)
  21.       return promiseRetry(promiseFactory, attemptsLeft);
  22.     throw new Error('Can not get data');
  23.   }
  24. }
  25.  
  26. const tryFetch = async (url, options) => {
  27.   const resp = await fetch(url, options);
  28.   if (!resp.ok)
  29.     throw new Error('ok is false');
  30.   return await resp.json();
  31. }
  32.  
  33. const getRate = async (currency) => {
  34.   // console.log({ currency, retry });
  35.   const { host, path, key } = API_EXCHANGE;
  36.   const url = `https://${host}/${path}${key}`;
  37.   const data = await tryFetch(url);
  38.   const rate = data.rates[currency];
  39.   return rate;
  40. };
  41.  
  42. const getTime = async () => {
  43.   const url = 'http://worldtimeapi.org/api/timezone/Europe/Kyiv';
  44.   const data = await tryFetch(url);
  45.   const { datetime } = data;
  46.   return new Date(datetime);
  47. }
  48.  
  49. const main = async () => {
  50.   try {
  51.     const rate = await promiseRetry(() => getRate('UAH'));
  52.     console.log({ rate });
  53.     // const time = await promiseRetry(() => getTime());
  54.     // console.log({ time });
  55.   } catch (err) {
  56.     console.error({ err });
  57.   }
  58. };
  59.  
  60. main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement