-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path24.RetryMechanismWithExponentialBackoff.js
More file actions
31 lines (24 loc) · 1.06 KB
/
24.RetryMechanismWithExponentialBackoff.js
File metadata and controls
31 lines (24 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 24. Retry Mechanism with Exponential Backoff
// Problem: Implement a retry mechanism for failed API calls with exponential backoff.
function retryWithExponentialBackoff(fn, retries, delay) {
return new Promise((resolve, reject) => {
const attempt = (retriesLeft, delayLeft) => {
fn()
.then(resolve)
.catch((err) => {
if (retriesLeft === 0) {
reject(err);
} else {
setTimeout(() => attempt(retriesLeft - 1, delayLeft * 2), delayLeft);
}
});
};
attempt(retries, delay);
});
}
// Test case
const apiCall = () => new Promise((resolve, reject) => Math.random() > 0.7 ? resolve('Success') : reject('Failed'));
retryWithExponentialBackoff(apiCall, 3, 1000).then(console.log).catch(console.error);
// Explanation:
// -Recursively calls the function with increasing delay (exponential backoff) on failure.
// -Stops after the specified retries or resolves if the function succeeds.