Skip to content

Instantly share code, notes, and snippets.

@garenyondem
Last active December 23, 2021 20:23
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 garenyondem/8d0ce0fdbaffb24c0fb7c1965dde3a7a to your computer and use it in GitHub Desktop.
Save garenyondem/8d0ce0fdbaffb24c0fb7c1965dde3a7a to your computer and use it in GitHub Desktop.
Recursively retry promise function by given number of times and arguments
module.exports = function (func, times, ...args) {
return new Promise((resolve, reject) => {
if (times <= 0) {
return reject(new Error('Invalid input times'));
}
func.apply(this, args).then((result) => {
if (!result) {
throw new Error('Func returned no results');
}
return resolve(result);
}).catch((err) => {
times -= 1;
if (times <= 0) {
return reject(err);
} else {
return promiseRetry(func, times, ...args);
}
}).catch((err) => {
return reject(err);
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment