Last active
December 23, 2021 20:23
-
-
Save garenyondem/8d0ce0fdbaffb24c0fb7c1965dde3a7a to your computer and use it in GitHub Desktop.
Recursively retry promise function by given number of times and arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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