Wednesday, June 11, 2014

Simple Promise Retry

I have recently been getting into the notions of asynchronous programming using the Promise pattern. I wrote this little piece of JavaScript code to act as a retry mechanism. In production you would probably want to add logging and maybe even a wait mechanism but I present the retry code in a bare form.

function retry(times, fn, paramArray) {
    if (times === 1) {
        return fn.apply(this, paramArray);
    } else {
        return fn.apply(this, paramArray)
            .catch (function (rejection) {
                return retry(times - 1, fn, paramArray)
            });
    }
}

I am using "catch" because that lines up with the promises library I am using. The parameter "fn" is the function that creates and returns a promise. Note that if it doesn't actually create the promise each time then this will be meaningless because the same promise will be repeatedly checked and the same resolution value will be found.

No comments:

Post a Comment