Created
March 23, 2022 12:01
-
-
Save monkeymonk/71ebde28a459df993941b7a2e4ec477a to your computer and use it in GitHub Desktop.
Retry n times
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
/** | |
* @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