Skip to content

Commit 770d629

Browse files
committed
Merge pull request #409 from uProxy/trevj-promise-retry-timeout
add optional timeout arg to promises.retry
2 parents 486ca2f + f98956b commit 770d629

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

src/promises/promises.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
/// <reference path='../../../third_party/typings/browser.d.ts' />
22

33
// Invokes f up to maxAttempts number of times, resolving with its result
4-
// on the first success and rejecting on maxAttempts-th failure.
5-
export const retry = <T>(f: () => Promise<T>, maxAttempts: number): Promise<T> => {
6-
return f().catch((e:Error) => {
7-
--maxAttempts;
8-
if (maxAttempts > 0) {
9-
return retry(f, maxAttempts);
10-
} else {
11-
return Promise.reject(e);
12-
}
4+
// on the first success and rejecting on the maxAttempts-th failure, waiting,
5+
// if specified, intervalMs ms between each attempt.
6+
export const retry = <T>(f: () => Promise<T>, maxAttempts: number, intervalMs = 0): Promise<T> => {
7+
return f().catch((e: Error) => {
8+
return maxAttempts <= 1 ? Promise.reject(e) : new Promise<T>((F, R) => {
9+
setTimeout(() => {
10+
retry(f, maxAttempts - 1, intervalMs).then(F, R);
11+
}, intervalMs);
12+
});
1313
});
1414
};
1515

0 commit comments

Comments
 (0)