Created
December 7, 2018 17:01
-
-
Save Wikiko/bf1b8cd449c1553b6e94567895a67cb4 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 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