Guest User

Untitled

a guest
Dec 18th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. // Welcome! require() some modules from npm (like you were using browserify)
  2. // and then hit Run Code to run your code on the right side.
  3. // Modules get downloaded from browserify-cdn and bundled in your browser.
  4.  
  5. const delay = (t) => new Promise((resolve, reject) => {
  6. setTimeout(() => resolve(delay.DELAY), t)
  7. })
  8.  
  9. delay.DELAY = Symbol('DELAY')
  10.  
  11. const timeout = (t) => (p) => Promise.race([p, delay(t)]).then(
  12. (value) => {
  13. console.log('timeout?', value === delay.DELAY)
  14. if (value === delay.DELAY) {
  15. throw 'Operation timed out'
  16. }
  17. return value
  18. }
  19. )
  20.  
  21. const retry = (n) => (f) => new Promise((resolve, reject) => {
  22. const attempt = (n) => {
  23. if (n > 0) {
  24. f().then(resolve).catch(() => attempt(n - 1))
  25. } else {
  26. return reject(retry.FAILED)
  27. }
  28. }
  29. attempt(n + 1)
  30. })
  31. retry.FAILED = Symbol('RETRY_FAILED')
  32.  
  33. const getStuff = (...$) => delay(100).then(() => [...$])
  34.  
  35. getStuff(1, 2, 3)
  36. .then((x) => console.log('success 1', x))
  37. .catch((x) => console.error('Failure 1', x));
  38.  
  39. (
  40. (...$) => timeout(20)(getStuff(...$))
  41. )(1, 2, 3)
  42. .catch((x) => console.error('Failure', x));
  43.  
  44. (
  45. (...$) => retry(2)(() => getStuff(...$))
  46. )(1, 2, 3)
  47. .then((x) => console.error('Success 2', x))
  48. .catch((x) => console.error('Failure 2', x));
  49.  
  50. (
  51. (...$) => retry(2)(() => timeout(20)(getStuff(...$)))
  52. )(1, 2, 3)
  53. .then((x) => console.error('Success 3', x))
  54. .catch((x) => console.error('Failure 3', x));
  55.  
  56.  
  57. // (...(() => P) => () => P) => (() => P) => () => P
  58. const compose = (...promiseFns) => promiseFns.reduce((acc, promiseFn) => (f) => acc(promiseFn(f)))
  59.  
  60. const retryTwiceWithTimeout = compose(
  61. (f) => () => retry(2)(f),
  62. (f) => () => timeout(20)(f())
  63. )
  64.  
  65. const getStuffSafe = (...$) => retryTwiceWithTimeout(() => getStuff(...$))()
  66.  
  67. getStuffSafe(1, 2, 3)
  68. .then((x) => console.log('success compose', x))
  69. .catch((x) => console.error('Failure compose', x))
Add Comment
Please, Sign In to add comment