Skip to content

Instantly share code, notes, and snippets.

@amiralitaheri
Created June 24, 2021 14:04
Show Gist options
  • Save amiralitaheri/aa5438e08f32488d7be4b037e710b995 to your computer and use it in GitHub Desktop.
Save amiralitaheri/aa5438e08f32488d7be4b037e710b995 to your computer and use it in GitHub Desktop.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* This function gets a async function and in case of error, it retries it
*
* @async
* @function retry
* @param {function} func - The async function
* @param {object} options - Retry options
* @param {Array} [options.args] - An array containing `func` arguments
* @param {number|function} [options.delay=0] - The amount of time to delay between each try in milliseconds
* @param {number} [options.tries=5] - The number of tries
* @param {function} [options.retryCondition] - A function that receives the error and determines whether retry should happen
* @returns {Promise}
*/
const retry = async (
func,
{ args = [], delay = 0, tries = 5, retryCondition }
) => {
try {
return await func(...args);
} catch (e) {
if (tries <= 0 || (retryCondition && !retryCondition(e))) {
throw e;
}
const _delay = typeof delay === "function" ? delay(tries) : delay;
_delay && (await wait());
return await retry(func, { args, delay, tries: --tries });
}
};
export default retry;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment