Created
December 7, 2018 16:41
-
-
Save Wikiko/3e6d6c3c984a8307305cdec3f843950d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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