Skip to content

Instantly share code, notes, and snippets.

@KATT
Created July 17, 2017 14:05
Show Gist options
  • Save KATT/ab7060f9c50937f5c8351e0af24fd287 to your computer and use it in GitHub Desktop.
Save KATT/ab7060f9c50937f5c8351e0af24fd287 to your computer and use it in GitHub Desktop.
retry async operation up to N times
/**
* retry async operaration up to N times
*
* usage:
* ```ts
* async fn() {
* const response = await retry(() => fetch('/endpoint/that/might/fail'), 3)
* }
* fn() // will retry fetch up to 3 times
* ```
* @param fn (async) function to retry
* @param maxTries
*/
async function retry<T>(fn: () => Promise<T>, maxTries = 1):Promise<T> {
let tries=0;
while (true) {
tries++;
try {
return await fn();
} catch (e) {
if (tries >= maxTries) {
throw e;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment