title: Promise Retry Design Patterns
body: <p><strong>Edit</strong></p>
  <ol>
  <li>Pattern that keep on retrying until the promise resolves (with <code>delay</code> and
  <code>maxRetries</code>).</li>
  <li>Pattern that keeps on retrying until the condition
  meets on the result (with <code>delay</code> and
  <code>maxRetries</code>).</li>
  <li>A memory efficient dynamic Pattern with unlimited retries (<code>delay</code> provided).</li>
  </ol>
  <p><strong>Code for #1.</strong> Keeps on retrying until promise resolves (any improvements community for the language etc?)</p>
  <pre><code>Promise.retry = function(fn, times, delay) {
      return new Promise(function(resolve, reject){
          var error;
          var attempt = function() {
              if (times == 0) {
                  reject(error);
              } else {
                  fn().then(resolve)
                      .catch(function(e){
                          times--;
                          error = e;
                          setTimeout(function(){attempt()}, delay);
                      });
              }
          };
          attempt();
      });
  };
  </code></pre>
  <p>Use</p>
  <pre><code>work.getStatus()
      .then(function(result){ //retry, some glitch in the system
          return Promise.retry(work.unpublish.bind(work, result), 10, 2000);
      })
      .then(function(){console.log('done')})
      .catch(console.error);
  </code></pre>
  <hr />
  <p><strong>Code for #2</strong> keep on retrying until a condition meets on the <code>then</code> result in a reusable way (condition is what will vary).</p>
  <pre><code>work.publish()
      .then(function(result){
          return new Promise(function(resolve, reject){
              var intervalId = setInterval(function(){
                  work.requestStatus(result).then(function(result2){
                      switch(result2.status) {
                          case &quot;progress&quot;: break; //do nothing
                          case &quot;success&quot;: clearInterval(intervalId); resolve(result2); break;
                          case &quot;failure&quot;: clearInterval(intervalId); reject(result2); break;
                      }
                  }).catch(function(error){clearInterval(intervalId); reject(error)});
              }, 1000);
          });
      })
      .then(function(){console.log('done')})
      .catch(console.error);
  </code></pre>