Last active
          April 5, 2017 02:23 
        
      - 
      
- 
        Save tweinfeld/4b12281766db702c4d52a0d484f01d1f to your computer and use it in GitHub Desktop. 
    Repeat a promise-generating function until resolution
  
        
  
    
      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
    
  
  
    
  | function repeatPromise(func, attempts = 10, delay = 1000) { | |
| let attemptNumber = 0; | |
| return (function internalTry() { | |
| attemptNumber++; | |
| if (attemptNumber > attempts) { | |
| return Promise.reject('Number of attempts exceeded'); | |
| } else { | |
| return func().catch(() => new Promise((resolve) => setTimeout(resolve, delay)).then(internalTry)); | |
| } | |
| })(); | |
| }; | |
| // Usage | |
| repeatPromise(()=>{ [... function that returns a promise ...] }, 15, 1000) | |
| .then(console.log) | |
| .catch(console.warn); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment