Skip to content

Instantly share code, notes, and snippets.

@Wikiko
Created December 7, 2018 16:41
Show Gist options
  • Save Wikiko/3e6d6c3c984a8307305cdec3f843950d to your computer and use it in GitHub Desktop.
Save Wikiko/3e6d6c3c984a8307305cdec3f843950d to your computer and use it in GitHub Desktop.
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;
});
}
}
// as Class...
class KeepTry {
constructor(times = 3, acceptableExceptions = []) {
this.currentTime = 1;
this._times = times;
this._acceptableExceptions = acceptableExceptions;
}
times(times) {
this._times = times;
return this;
}
acceptableExceptions(acceptableExceptions) {
this._acceptableExceptions = acceptableExceptions;
return this;
}
keepTry(fn) {
this.fn = fn;
return this;
}
async run(...args) {
for (let currentTime = 1; currentTime <= this._times; currentTime++) {
try {
return await this.fn(...args);
} catch (err) {
if (!this._acceptableExceptions.includes(err)) {
throw err;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment