Exercise 3: Retry Wrapper (3 tries)
Problem Statement
Create a function `retry(fn, tries=3)`. Retry on failure, throw on last fail.
Sample Output:
await retry(() => fetchAPI(), 3) // If succeeds on 1st try: returns result // If fails 2 times, succeeds on 3rd: returns result // If all 3 fail: throws last error
Solution
const retry = async (fn, tries = 3) => {
let err;
for (let i = 0; i < tries; i++) {
try { return await fn(); } catch (e) { err = e; }
}
throw err;
};Explanation
Overall Goal:
- Function ko retry karna: fail ho to phir se try karna.
- Maximum tries limit: infinite retry nahi.
Line 1: Async function
const retry = async (fn, tries = 3) => {fn→ function jo retry hona hai (Promise return karta hai).tries = 3→ default 3 attempts.
Line 2: Error storage
let err;→ last error store karne ke liye variable.
Line 3: Retry loop
for (let i = 0; i < tries; i++) {i < tries→ maximumtriestimes loop chalega.
Line 4: Try and catch
try { return await fn(); } catch (e) { err = e; }try→ function ko execute karo.await fn()→ Promise resolve hone tak wait.- Agar success →
return(loop break, function exit). - Agar fail →
catchblock: err = e→ error store karo (last error track).- Loop continue (next iteration, retry).
Line 5: Throw last error
throw err;- Agar sabhi tries fail ho gaye → last error throw.
Example:
retry(() => fetchAPI(), 3)- Try 1: fail → retry.
- Try 2: fail → retry.
- Try 3: success → return result.
Real world:
- Network calls: flaky connections handle karna.
- API retries: temporary server errors.
- Database operations: connection retries.