Home > Back-end >  Reusable retry in TypeScript
Reusable retry in TypeScript

Time:01-09

This function takes the function that is to be retried as its first argument, and some additional options as its second. As long as there are tries available the given function will be called and retried until either the function returns a result, or we run out of tries. Either the result of the function or the last error it throws are exposed to the outside world.

The request is:

I want to Type this function so that any function that doesn’t require any arguments can be retried and that there are no type errors in index.ts without editing the index file. The return type of the original function must be preserved, wrapped in a promise.

function wait(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export async function retryFn(fn, { tries, interval }) {
  try {
    return fn();
  } catch (e) {
    const newTries = tries - 1;

    if (newTries === 0) {
      throw e;
    }

    await wait(interval);

    return retryFn(fn, { tries: newTries, interval });
  }
}

CodePudding user response:

You could use RxJs retry operator. It takes number, that represents the number of tries you would like to take. And as a result value you could wrap it in an observable instead of a Promise. I think it is a better solution

CodePudding user response:

type FunctionWithoutParams = () => any;
type Config = { tries: number, interval: number};

export async function retryFn<T extends FunctionWithoutParams>(
    fn : T,
    { tries, interval }: Config
) : Promise<ReturnType<T>>
{
    //...
}

This function type will ensure fn is constrained so that only arguments with types that extend () => any are usable. () => any represents any function that takes no arguments (and returns a value of type any).

ReturnType is a helpful utility type that we can use to grab the return type of this generic function type.

  •  Tags:  
  • Related