Skip to content

Instantly share code, notes, and snippets.

@madox2
Created August 7, 2016 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madox2/6f5b31125a3b0b8717eda1db61679c69 to your computer and use it in GitHub Desktop.
Save madox2/6f5b31125a3b0b8717eda1db61679c69 to your computer and use it in GitHub Desktop.
retry promise extension
/**
* This script uses ECMAScript 2015 syntax.
* Check compatibility for your environment.
* To run it in nodejs (5.8.0) you need to enable feature flags:
* --harmony_destructuring --harmony_rest_parameters --harmony_default_parameters
*/
"use strict"
/**
* This will create callback function which tries to execute handler given times and returns promise.
* It will perserve and forward original arguments to the handler.
*
* @param {function} handler - function to be retried
* @param {object} options - reTry options
* @param {integer} options.times - number of times to try execute function
* @param {integer} options.timeout - timeout applied between attempts
* @param {function} options.log - optional logging function
*/
function reTry(handler, { times = 3, timeout = 100, log = (() => undefined) } = {}) {
return (...args) => function tryIt() {
return Promise.resolve().then(() => handler(...args)).catch(err => {
if (times > 0) {
log(`Retrying promise, remaining attempts: ${times - 1}`, err)
return new Promise(resolve => setTimeout(resolve, timeout)).then(() => tryIt(handler, args, --times));
}
return Promise.reject(err);
});
}();
}
let failedCount = 2;
function sumArray(arr) {
if (failedCount) {
failedCount--;
throw new Error('Expected error');
}
return arr.reduce((a, b) => a + b);
}
const opts = { times: 4, timeout: 1000, log: console.error };
Promise.resolve([1, 2, 3, 4])
.then(reTry(sumArray, opts))
.then(sum => console.log(`Sum of array: ${sum}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment