Skip to content

Commit 9ecf253

Browse files
committed
feat: add request retry
1 parent 6413ca4 commit 9ecf253

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

js/request_retry.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
function requestWithRetry1(url, attempts = 3) {
2+
return new Promise(function (resolve, reject) {
3+
fetch(url)
4+
.then(function (result) {
5+
resolve(result);
6+
})
7+
.catch(function (error) {
8+
attempts--; // 2, 1, 0
9+
10+
if (attempts === 0) {
11+
reject(error);
12+
} else {
13+
setTimeout(() => {
14+
requestWithRetry1(url, attempts);
15+
}, 3000);
16+
}
17+
});
18+
});
19+
}
20+
21+
async function requestWithRetry2(url, attempts = 3) {
22+
const retry = async (attempt = 1) => {
23+
try {
24+
return await fetch(url);
25+
} catch (error) {
26+
if (attempt >= attempts) {
27+
throw error;
28+
}
29+
30+
// Use an increasing delay to prevent flodding the
31+
// server with requests in case of a short downtime.
32+
const delay = 1000 * attempt;
33+
34+
return new Promise((resolve) =>
35+
setTimeout(() => resolve(retry(attempt + 1)), delay)
36+
);
37+
}
38+
};
39+
40+
return retry;
41+
}

0 commit comments

Comments
 (0)