Last active
April 21, 2016 02:08
-
-
Save oscarkuo/6685cc9f4e8bb52f4ad274bd74924bd5 to your computer and use it in GitHub Desktop.
Promise retry
This file contains 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
'use strict'; | |
let i = 0; | |
const fn = () => { | |
if (i++ < 5) | |
throw new Error(`crap ${i}`); | |
return "success"; | |
}; | |
const pfn = (resolve, reject) => { | |
try { | |
resolve(fn()); | |
} catch (ex) { | |
console.log(ex); | |
reject(ex); | |
} | |
}; | |
const ppfn = () => { | |
return new Promise(pfn); | |
} | |
const retry = (retries, fn) => { | |
return fn().catch((e) => { | |
if (retries <= 0) { | |
throw e; | |
} | |
console.log('retry attempt ' + retries + ' left'); | |
// return a promise from then(), the next then() will be on the returned promise | |
// http://stackoverflow.com/questions/27715275/whats-the-difference-between-returning-value-or-promise-resolve-from-then | |
return retry(retries - 1, fn); | |
}); | |
}; | |
retry(7, ppfn); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment