Advanced · 12 min
Bounded retries
Retry a known temporary failure while keeping attempts finite.
Set a clear bound
A retry loop needs a maximum number of attempts and a final failure path. Retry only failures the operation identifies as temporary.
let calls = 0;
async function load() { calls += 1; if (calls < 2) throw new Error("Temporary"); return "Ready"; }
let result;
for (let attempt = 1; attempt <= 2; attempt += 1) {
try { result = await load(); break; }
catch (error) { if (attempt === 2) throw error; }
}
console.log(result);
console.log(calls);Output
Ready 2
Preserve permanent failures
Invalid input should not be retried. In network applications, also consider backoff, cancellation, and whether repeating the operation is safe.
async function load() { const error = new Error("Invalid input"); error.retryable = false; throw error; }
try { await load(); } catch (error) { console.log(error.retryable ? "Retry" : "Stop"); }Output
Stop
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Allow the second attempt
The local operation fails once, then succeeds. Let it try at most twice and display the result.
Change the attempt limit from 1 to 2.