Skip to content

Instantly share code, notes, and snippets.

@okmttdhr
Created February 4, 2020 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okmttdhr/c056e28fc63781bad0cd9e95e33625cf to your computer and use it in GitHub Desktop.
Save okmttdhr/c056e28fc63781bad0cd9e95e33625cf to your computer and use it in GitHub Desktop.
Retry promise with incremental backoff in TypeScript
export const retry = (fn: () => Promise<any>, timeout = 1000, retries = 5) =>
new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch(() => {
setTimeout(() => {
const retriesLeft = retries - 1;
if (retries < 0) {
return reject('maximum retries exceeded');
}
retry(fn, timeout * 2, retriesLeft).then(resolve);
}, timeout);
});
});
@okmttdhr
Copy link
Author

okmttdhr commented Feb 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment