Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Welcome! require() some modules from npm (like you were using browserify)
- // and then hit Run Code to run your code on the right side.
- // Modules get downloaded from browserify-cdn and bundled in your browser.
- const delay = (t) => new Promise((resolve, reject) => {
- setTimeout(() => resolve(delay.DELAY), t)
- })
- delay.DELAY = Symbol('DELAY')
- const timeout = (t) => (p) => Promise.race([p, delay(t)]).then(
- (value) => {
- console.log('timeout?', value === delay.DELAY)
- if (value === delay.DELAY) {
- throw 'Operation timed out'
- }
- return value
- }
- )
- const retry = (n) => (f) => new Promise((resolve, reject) => {
- const attempt = (n) => {
- if (n > 0) {
- f().then(resolve).catch(() => attempt(n - 1))
- } else {
- return reject(retry.FAILED)
- }
- }
- attempt(n + 1)
- })
- retry.FAILED = Symbol('RETRY_FAILED')
- const getStuff = (...$) => delay(100).then(() => [...$])
- getStuff(1, 2, 3)
- .then((x) => console.log('success 1', x))
- .catch((x) => console.error('Failure 1', x));
- (
- (...$) => timeout(20)(getStuff(...$))
- )(1, 2, 3)
- .catch((x) => console.error('Failure', x));
- (
- (...$) => retry(2)(() => getStuff(...$))
- )(1, 2, 3)
- .then((x) => console.error('Success 2', x))
- .catch((x) => console.error('Failure 2', x));
- (
- (...$) => retry(2)(() => timeout(20)(getStuff(...$)))
- )(1, 2, 3)
- .then((x) => console.error('Success 3', x))
- .catch((x) => console.error('Failure 3', x));
- // (...(() => P) => () => P) => (() => P) => () => P
- const compose = (...promiseFns) => promiseFns.reduce((acc, promiseFn) => (f) => acc(promiseFn(f)))
- const retryTwiceWithTimeout = compose(
- (f) => () => retry(2)(f),
- (f) => () => timeout(20)(f())
- )
- const getStuffSafe = (...$) => retryTwiceWithTimeout(() => getStuff(...$))()
- getStuffSafe(1, 2, 3)
- .then((x) => console.log('success compose', x))
- .catch((x) => console.error('Failure compose', x))
Add Comment
Please, Sign In to add comment