Created
February 25, 2021 14:21
-
-
Save jdrzejb/e68e08102e38db1fe5395d4daafc99c3 to your computer and use it in GitHub Desktop.
promise retry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function retryPromise<T>(fn: () => Promise<T>, retriesLeft = 5, interval = 375): Promise<T> { | |
return new Promise((resolve, reject) => { | |
fn() | |
.then(resolve) | |
.catch(error => { | |
setTimeout(() => { | |
if (retriesLeft === 1) { | |
// reject('maximum retries exceeded'); | |
reject(error); | |
return; | |
} | |
// math formula (375 2^(5 - n)) -> it allows to increase request timeout, like 375, 750, 1500, 3000, 6000. | |
// Math.max safeguard is here to make sure that we do not reach backoff values below 375ms. | |
const timeout = Math.max(375 * 2 ** (5 - retriesLeft), 300, 375); | |
// Passing on "reject" is the important part | |
retryPromise(fn, retriesLeft - 1, timeout).then(resolve, reject); | |
}, interval); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment