Skip to content

Instantly share code, notes, and snippets.

@Convicted202
Created February 8, 2018 11:50
Show Gist options
  • Save Convicted202/a8aac00a1dd6d919579187004655e397 to your computer and use it in GitHub Desktop.
Save Convicted202/a8aac00a1dd6d919579187004655e397 to your computer and use it in GitHub Desktop.
Promises retry maxTries
function waitFor (time, promiseFn = () => {}) {
const wait = new Promise(resolve => {
setTimeout(resolve, time);
});
return Promise.all([promiseFn, wait]).then(
args => args[0] && typeof args[0] === 'function' && args[0](),
() => Promise.reject('Error in waitFor')
);
}
const retry = (func, maxTries, delay, onFail = () => {}) => {
return Promise.resolve()
.then(func)
.catch(
err =>
maxTries > 1
? Promise.resolve()
.then(onFail.bind(null, maxTries))
.then(() =>
waitFor(
delay,
retry.bind(null, func, --maxTries, delay, onFail)
)
)
: Promise.reject(err)
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment