|
| 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