Last active
July 27, 2020 08:41
-
-
Save HaNdTriX/9b933ef17f08c5f8436528d00e87fa12 to your computer and use it in GitHub Desktop.
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
/** | |
* Allows to repeatedly call | |
* an async code block | |
* | |
* @callback callback | |
* @callback [filterError] Allows to differentiate beween different type of errors | |
* @param {number} [maxRetries=Infinity] | |
*/ | |
function asyncRetry( | |
callback, | |
{ filterError = (error) => true, maxRetries = Infinity } = {} | |
) { | |
// Initialize a new counter: | |
let tryCount = 0; | |
// Next return an async IIFY that is able to | |
// call itself recursively: | |
return (async function retry() { | |
// Increment out tryCount by one: | |
tryCount++; | |
try { | |
// Try to execute our callback: | |
return callback(); | |
} catch (error) { | |
// If our callback throws any error lets check it: | |
if (filterError(error) && tryCount <= maxRetries) { | |
// Recursively call this IIFY to repeat | |
return retry(); | |
} | |
// Otherwise rethrow the error: | |
throw error; | |
} | |
})(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo
Try 2 times:
Try 2 times & only retry on
DOMError
s:Infine Retry: (Don't do this!)
Catch Puppeteer timeout