Fetch with retry in JavaScript
Retries a failed request with a growing delay, because networks fail for a moment and then do not.
async function fetchRetry(url, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try {
const res = await fetch(url);
if (res.ok) return res.json();
throw new Error(`HTTP ${res.status}`);
} catch (err) {
if (i === attempts - 1) throw err;
}
}
}
Keywords and builtins used here
asyncawaitcatchconstforfunctionifletreturnthrowtry
The run, in numbers
- Lines
- 11
- Characters to type
- 246
- Tokens
- 84
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 46 seconds.
Step 4 of 4 in Canceling & limiting, step 18 of 19 in Promises & async.