Skip to content

Instantly share code, notes, and snippets.

@Wikiko
Created December 7, 2018 17:01
Show Gist options
  • Save Wikiko/bf1b8cd449c1553b6e94567895a67cb4 to your computer and use it in GitHub Desktop.
Save Wikiko/bf1b8cd449c1553b6e94567895a67cb4 to your computer and use it in GitHub Desktop.
`// function keepTry(fn, times = 3, acceptableExceptions = []) {
// let currentTime = 1;
// return function toExecute(...args) {
// try {
// const result = fn(...args);
// } catch (err) {
// if (acceptableExceptions.includes(err) && currentTime <= times) {
// currentTime++;
// return toExecute(...args);
// }
// throw err;
// }
// }
// }
function toPromise(fn, ...args) {
try {
return Promise.resolve(fn(...args));
} catch (err) {
return Promise.reject(err);
}
}
function keepTry(times = 3, acceptableExceptions = [], fn) {
let currentTime = 1;
return function toExecute(...args) {
//Converts all to promise, if fn return promise it flatten that if not, it wrap that.
return toPromise(fn, ...args)
.catch(err => {
currentTime++;
if (currentTime <= times && acceptableExceptions.includes(err)) {
return toExecute(...args);
}
throw err;
});
}
}
function keepTry(times = 3, acceptableExceptions = [], fn) {
return async function toExecute(...args) {
for (let currentTime = 1; currentTime <= times; currentTime++) {
try {
//Converts all to promise, if fn return promise it flatten that if not, it wrap that.
return await toPromise(fn, ...args);
} catch (err) {
if (!acceptableExceptions.includes(err)) {
throw err;
}
}
}
}
}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment