-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRetry.js
More file actions
28 lines (24 loc) · 659 Bytes
/
Copy pathRetry.js
File metadata and controls
28 lines (24 loc) · 659 Bytes
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
// retry promises after n times
async function retry(asyncFn, retries, delay, finalError) {
if (retries === 0) {
return Promise.reject(finalError);
} else {
try {
const val = await asyncFn();
return val;
} catch {
console.log("Retrying...", retries, "attempts left");
await new Promise((resolve) => setTimeout(resolve, delay));
return retry(asyncFn, retries - 1, delay, finalError);
}
}
}
function asycnFunction() {
return new Promise((_, reject) => {
reject("Error message");
});
}
const result = retry(asycnFunction, 3, 1000, "bye bye");
result.then().catch((val) => {
console.log(val);
});