startReattempting.js

by joplomacedo

JavaScript

const startReattempting = ({
  cb,
  initialError,
  onFail = () => {},
  onSuccess = () => {},
  maxAttempts = 10,
  attemptInterval = 1000
}) => {

  let currentAttempt = 0;

  const executeAttempt = () => {

    ++currentAttempt;

    setTimeout(() => {
      cb()
        .then((res) => {
          onSuccess(res);
        })
        .catch((err) => {
          if (currentAttempt < maxAttempts) {
            executeAttempt();
          } else {
            onFail(initialError);
          }
        })
    }, attemptInterval);
  };

  executeAttempt();
}