title: Retry on Javascript.Promise.reject a limited number of times or until success
body: <p>I have a function say <code>myMainFunction</code> that is called from a client, that in turn calls <code>mypromisified</code> function.</p>
  
  <p><strong>Scenario:</strong>
  <code>mypromisified</code> function can fail intermittently and I need to call this function with a delay (at an exponential increase) until success or until max no of tries reached.</p>
  
  <p><strong>What I have so far</strong></p>
  
  <p>The following code illustrates my scenario and repeats itself until success, <em>but it tries indefinitely and not until certain count is reached</em></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// called once from the client
  myMainFuntion();
  
  function rejectDelay(delay, reason) {
     // call main function at a delayed interval until success 
     // but would want to call this only a limited no of times
      setTimeout(() =&gt; {
        myMainFuntion(); // calling main function again here but with a delay
      }, delay);
  }
  
  
  function myMainFuntion() {
    var delay = 100;
    var tries = 3;
    tryAsync().catch(rejectDelay.bind(null, delay));
  }
  
  function tryAsync() {
    return new Promise(function(resolve, reject) {
      var rand = Math.random();
      console.log(rand);
      if (rand &lt; 0.8) {
        reject(rand);
      } else {
        resolve();
      }
    });
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><code>while</code> loop inside the <code>rejectDelay</code> would certainly not work as the counter would increment even before the actual function inside setInterval is executed, so am unsure as to how to go about this? so...</p>
  
  <p>I tried <code>promisifying</code> the <code>setInterval</code> something like this knowing it will fail :( as it doesnt decrement the counter, but not sure how to get it right either . </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function rejectDelay(delay, maximumTries, reason) {
    return new Promise(function (resolve, reject) {
      console.log(tries + ' remaining');
      if (--maximumTries &gt; 0) {
        setTimeout(function() {
          foo();
        }, 500);
      } 
    });
  }
  function myMainFunction() {
    var delay = 100;
    var maximumTries = 3;
    tryAsync().catch(rejectDelay.bind(null, delay, maximumTries));
  }</code></pre>
  </div>
  </div>
  </p>