Created
August 2, 2019 17:04
-
-
Save tusharf5/127f4fff88ca470753842e88a39b8842 to your computer and use it in GitHub Desktop.
Javascript function to retry a promise n no. of times before rejecting.
This file contains 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
/** | |
* Retries a promise n no. of times before rejecting. | |
*/ | |
async function retryPromise(promise, nthTry) { | |
try { | |
const res = await promise; | |
return res; | |
} catch (e) { | |
if (nthTry === 1) { | |
return Promise.reject(e); | |
} | |
console.log("retrying", nthTry, "time"); | |
return retryPromise(promise, nthTry - 1); | |
} | |
} | |
/** | |
* Retries a promise infinite no. of times. Don't use it ever. | |
* This is recursion without a base condition. | |
*/ | |
async function infiniteRetryPromise(promise, nthTry = 0) { | |
try { | |
const res = await promise; | |
return res; | |
} catch (e) { | |
console.log("retrying", nthTry, "time"); | |
return infiniteRetryPromise(promise, nthTry + 1); | |
} | |
} | |
/** | |
* Util function to return a promise which is resolved in provided milliseconds | |
*/ | |
function waitFor(millSeconds) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(); | |
}, millSeconds); | |
}); | |
} | |
/** | |
* Retries a promise n no. of times before rejecting. | |
* Retries a promise after waiting for {delayTime} milliseconds on a reject. | |
*/ | |
async function retryPromiseWithDelay(promise, nthTry, delayTime) { | |
try { | |
const res = await promise; | |
return res; | |
} catch (e) { | |
if (nthTry === 1) { | |
return Promise.reject(e); | |
} | |
console.log("retrying", nthTry, "time"); | |
await waitFor(delayTime); | |
return retryPromiseWithDelay(promise, nthTry - 1, delayTime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment