Skip to content

Commit 4886aac

Browse files
committed
Add real-life example
1 parent 2b01b5d commit 4886aac

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

JavaScript/9-retry.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'use strict';
2+
3+
const DEFAULT_RETRY = 3;
4+
5+
const httpGet = async ({ url, retry = DEFAULT_RETRY }) => {
6+
console.log({ url, retry });
7+
const res = await fetch(url).catch(() => ({ ok: false }));
8+
if (!res.ok) {
9+
const attemptsLeft = retry - 1;
10+
if (attemptsLeft > 0) return httpGet({ url, retry: attemptsLeft });
11+
throw new Error('Can not get data');
12+
}
13+
return res.json();
14+
};
15+
16+
const main = async () => {
17+
try {
18+
const key = '1f43ea96b1e343fe94333dd2b97a109d';
19+
const url = 'https://openexchangerates.org/api/latest.json?app_id=' + key;
20+
const data = await httpGet({ url });
21+
const rate = data.rates['UAH'];
22+
console.log({ rate });
23+
} catch (err) {
24+
console.error({ err });
25+
}
26+
};
27+
28+
main();

0 commit comments

Comments
 (0)