-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRetryPromises.js
46 lines (43 loc) · 1.31 KB
/
RetryPromises.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
async function getData() {
const randomNumber = Math.ceil(Math.random() * 3);
console.log("Random Number Generated :", randomNumber);
if (randomNumber !== 1) {
throw new Error("Failed - Unable to generate the right number.");
}
return randomNumber;
}
async function retry(asyncFn, retries, delay, errorMessage) {
for (let i = 0; i < retries; i++) {
try {
console.log("Trying to execute the function.");
const output = await asyncFn();
console.log("Successful Response : ", output);
return output;
} catch (err) {
console.log(`Attempt ${i + 1} failed.`);
if (i < retries - 1) {
console.log("Retrying...");
await new Promise((resolve) => setTimeout(resolve, delay + delay));
} else {
console.log(errorMessage);
return Promise.reject(errorMessage);
}
}
}
}
retry(getData, 3, 200, "Failed")
.then((result) => console.log("Final Result:", result))
.catch((err) => console.log("Final Error:", err));
//SAMPLE OUTPUT
// Trying to execute the function.
// Random Number Generated : 3
// Attempt 1 failed.
// Retrying...
// Trying to execute the function.
// Random Number Generated : 3
// Attempt 2 failed.
// Retrying...
// Trying to execute the function.
// Random Number Generated : 1
// Successful Response: 1
// Final Result: 1