Created
July 17, 2017 14:05
-
-
Save KATT/ab7060f9c50937f5c8351e0af24fd287 to your computer and use it in GitHub Desktop.
retry async operation up to N times
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
/** | |
* 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