title: Repeat a Promise until it's not rejected or reach a timeout
body: <p>I'm still a Promise noob and am trying to figure out how to have my Promise repeat itself.</p>
  
  <p>have an ES6 promise that rejects if some global flag is not set. I need it to retry every 500ms until either:</p>
  
  <ul>
  <li>the promise returns a resolve,</li>
  <li>or a max number of attempts are reached (lets say 10).</li>
  </ul>
  
  <p>Since Promises are async, I don't really want to use a <code>setInterval()</code> check, because I don't think that'd work correctly with asynchronous code. I need the checking to terminate as soon as the promise is resolved successfully ( or timeout reached ).</p>
  
  <p>I'm using ES6 + React + ES6 Promises (so no Q or Bluebird-specific answers, please!)</p>
  
  <p><a href="http://jsfiddle.net/2k2kz9r9/8/" rel="noreferrer">http://jsfiddle.net/2k2kz9r9/8/</a></p>
  
  <pre><code>// CLASS
  class Test extends React.Component {
      constructor() {
        this.state = {
          status: 'setting up..',
        }
      }
      componentDidMount() {
        // TODO: how do I get this to loop with a timeout?
        this.createSlot()
          .then((slot) =&gt; {
            this.setState({
              status: slot
            });
          })
          .catch((e) =&gt; {
            this.setState({
              status: e.message
            });
          })
      }
      createSlot() {
        return new Promise((resolve, reject) =&gt; {
          if (!this.checkIsReady()) {
            reject(new Error('Global isnt ready yet'));
          }
          // more stuff here but going to resolve a string for simplicity sake
          resolve('successful!');
        });
      }
      checkIsReady() {
        return window.globalThing &amp;&amp; window.globalThing === true;
      }
      render() {
          return ( &lt;div&gt;{this.state.status}&lt;/div&gt; );
      }
  }
  
  
  
  
  
      // RENDER OUT
      React.render(&lt; Test/&gt; , document.getElementById('container'));
  </code></pre>
  
  <p><strong>EDIT: function based on current feedback:</strong></p>
  
  <pre><code>  createSlot(tries) {
      const _this = this;
      return new Promise(function cb(resolve, reject) {
        console.log(`${tries} remaining`);
        if (--tries &gt; 0) {
          setTimeout(() =&gt; {
            cb(resolve, reject);
          }, 500);
        } else {
          const { divId, adUnitPath } = _this;
          const { sizes } = _this.props;
  
          // if it's not, reject
          if (!_this.isPubadsReady()) {
            reject(new Error('pubads not ready'));
          }
          // if it's there resolve
          window.googletag.cmd.push(() =&gt; {
            const slot = window.googletag
              .defineSlot(adUnitPath, sizes, divId)
              .addService(window.googletag.pubads());
            resolve(slot);
          });
        }
      });
    }
  </code></pre>