Angular Promise trying Wrapper Sometimes I need to repeat an execution of rejected promises several times, for example, to fetch some data over internet.
There is a wrapper, which accepts Promise and tryCount:



function tryPromise(f, tryCount) {
  return f().then(null, function(v) {
    tryCount--;
    if (tryCount &gt; 0) {
      return $q.reject(v);
    }
    return tryPromise(f, tryCount);
  });
}




Is there some hidden troubles?
Well, first of all you aren't trying a promise. What you're really doing is trying out a function that returns a promise. So the name is already misleading. Try something better.

Next, f and v doesn't really tell me anything. Only when I read through the code did I realize f was the function to try out and v is supposed to be a value. Additionally, even if you name v a value, it's still not correct. Most reject handlers often pass an error object.

Code that requires one to actually read to understand is a bad practice. In this case it's negligible due to the size of the function. But if you're in larger codebases, it's a nightmare to maintain. Name your functions and variables meaningfully.

Lastly, your function doesn't allow for function arguments. It would be nice to at least accept argument 3 onwards as the arguments, or accept an array that would be the arguments.

My take on it would be:

function tryPromiseFunction(functionToTry, retries, ...args){
  return functionToTry(...args).then(null, error =&gt; {
    return retries &gt; 0 ? tryPromiseFunction(functionToTry, retries - 1, ...args)
                       : Promise.reject(error);
  });
}