Last active
November 14, 2017 10:50
-
-
Save jt3k/4bd1d58ee46035cc6dbc9200cc7f3595 to your computer and use it in GitHub Desktop.
promise with attempts
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
// fake fetch-data function | |
function fetch () { | |
const isFailure = Math.random() > .9; | |
console.log(isFailure); | |
return isFailure ? Promise.resolve({data: 'data'}) : Promise.reject(); | |
} | |
// building promise with attempts | |
function getData(attempt = 3) { | |
let p = fetch(); | |
let c = attempt; | |
while (--c) { | |
p = p.catch(fetch); | |
} | |
return p.catch(() => Promise.reject(new Error(`did not work after ${attempt} attempts`))); | |
} | |
// example of using | |
getData(3).catch(err => {console.error(err)}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment