Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Last active July 27, 2020 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HaNdTriX/9b933ef17f08c5f8436528d00e87fa12 to your computer and use it in GitHub Desktop.
Save HaNdTriX/9b933ef17f08c5f8436528d00e87fa12 to your computer and use it in GitHub Desktop.
/**
* 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;
}
})();
}
@HaNdTriX
Copy link
Author

Demo

Try 2 times:

await asyncRetry(() => {
  // Put your async code here
}, { maxRetries = 2 })

Try 2 times & only retry on DOMErrors:

// Only retry on specific errors
await asyncRetry(() => {
  // Put your async code here
}, { 
  maxRetries = 2,
  filterError: (error) => error instance of DOMError
})

Infine Retry: (Don't do this!)

// Only retry on specific errors
await asyncRetry(() => {
  // Put your async code here
})

Catch Puppeteer timeout

const puppeteer = require('puppeteer')

// Only retry on specific errors
await asyncRetry(() => {
  // Put your async code here
}, { 
  maxRetries = 2,
  filterError: (error) => error instanceof puppeteer.errors.TimeoutError
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment