Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX

HaNdTriX/asyncRetry.js

Last active Jul 27, 2020
Embed
What would you like to do?
/**
* 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

This comment has been minimized.

Copy link
Owner Author

@HaNdTriX HaNdTriX commented Jul 27, 2020

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
You can’t perform that action at this time.