Created
December 21, 2022 06:51
-
-
Save justsml/7e52521a0af50fa590be57d5b4593120 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
/** | |
* A **Smarter** retry wrapper with currying! | |
*/ | |
function retryCurry(fn, retriesLeft = 5) { | |
const retryFn = (...args) => fn(...args) | |
.catch(err => retriesLeft > 0 | |
? retryFn(fn, retriesLeft - 1) | |
: Promise.reject(err) | |
}) | |
return retryFn | |
} | |
const getJson = (url) => fetch(url) | |
.then(response => response.json()) | |
// Usage | |
const retryGetJson = retryCurry(getJson, 3); | |
// Now you can pass any arguments through to your function! | |
retryGetJson('https://api.github.com/orgs/elite-libs') | |
.then(console.log) | |
.catch(console.error) |
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
/** Basic retry wrapper for Promises */ | |
function retryPromise(fn, retriesLeft = 5) { | |
return fn() | |
.catch(err => retriesLeft > 0 | |
? retryPromise(fn, retriesLeft - 1) | |
: Promise.reject(err) | |
}) | |
} | |
const getJson = (url) => fetch(url) | |
.then(response => response.json()) | |
// Usage | |
retry(() => getJson('https://api.github.com/orgs/elite-libs')) | |
.then(console.log) | |
.catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment