create a function that takes another function and retries up to three times if it fails in javascript

index.tsx
function retry(func) {
  let attempts = 0;
  return function(...args) {
    try {
      return func(...args);
    } catch(error) {
      if(attempts < 2) {
        attempts++;
        return retry(func)(...args);
      } else {
        throw error;
      }
    }
  }
}
269 chars
16 lines

Here, we define a function retry that takes another function func as input. The retry function returns a closure that can be called with arbitrary arguments, representing the arguments for func. Within this closure, we try to execute func(...args) and return its result if successful. If func throws an error, we catch the error and check if we have already retried the function three times. If we have retried three times, we simply re-throw the error. If we have not retried three times, we increment the attempts counter and recursively call the closure returned by retry(func) with the same arguments (...args).

By using recursion and a closure, we are able to retry the func function up to three times if it fails, without having to modify the original implementation of func or having to replicate its argument list in the retry function.

gistlibby LogSnag