Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Created March 23, 2022 12:01
Show Gist options
  • Save monkeymonk/71ebde28a459df993941b7a2e4ec477a to your computer and use it in GitHub Desktop.
Save monkeymonk/71ebde28a459df993941b7a2e4ec477a to your computer and use it in GitHub Desktop.
Retry n times
/**
* @example
*.try {
* const result = await retry((attempt) => {
* if ( Math.ceil(Math.random() >= .5) ) {
* return 'ok';
* }
*
*. console.log('-> nope');
* throw new Error('Failed after ' + attempt + ' tries');
* }, 5);
*. console.log('-> success', result);
* } catch(err) {
* console.log('-> failed', err);
* }
*
* @param callback
* @param maxAttempts (default: 2)
* @param delayInSeconds (default: .1)
* @returns {Promise<unknown>}
*/
export async function retry(callback, maxAttempts = 2, delayInSeconds = .1) {
const execute = async (attempt) => {
try {
return await callback(attempt);
} catch (err) {
if (attempt === maxAttempts) {
throw new Error(err);
} else {
return await new Promise((resolve) => setTimeout(() => resolve(execute(++attempt)), delayInSeconds));
}
}
};
return await execute(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment