Skip to content

Instantly share code, notes, and snippets.

@jt3k
Last active November 14, 2017 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jt3k/4bd1d58ee46035cc6dbc9200cc7f3595 to your computer and use it in GitHub Desktop.
Save jt3k/4bd1d58ee46035cc6dbc9200cc7f3595 to your computer and use it in GitHub Desktop.
promise with attempts
// 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