title: How to retry a Cloud Firestore transaction in a Cloud Function until state == true
body: <h1>The issue</h1>
  
  <p>I have a Cloud Function which updates a Cloud Firestore document, based on changes in a document <code>state</code> field.  These updates <strong>must</strong> happen in a particular order.  When two changes are made in quick succession, there's no guarantee that the Cloud Functions will run in the correct sequence.  Is there a way to have a Cloud Firestore transaction retry until it succeeds or times out?</p>
  
  <ol>
  <li><code>Document.state</code> is set to <code>stage1</code></li>
  <li><code>Document.state</code> is updated to <code>stage2</code></li>
  <li><code>Document.state</code> is updated to <code>stage3</code></li>
  <li>Cloud Function is triggered and reads <code>stage3</code></li>
  <li>Cloud Function is triggered and reads <code>stage2</code></li>
  </ol>
  
  <p>In the Cloud Functions documentation, it discusses the ability to retry transactions on failure.  However, this option is greyed out in the Cloud Functions section of the GCP Console (not shown in the Firebase Console)</p>
  
  <h1>Sample code</h1>
  
  <h2>Variables passed in</h2>
  
  <pre><code>myDocumentRef: db.doc('myCollection/myDocument')
  newState: stage3
  </code></pre>
  
  <h2>Transaction code</h2>
  
  <pre><code>var transaction = db.runTransaction(t =&gt; {
      return t.get(myDocumentRef)
          .then(doc =&gt; {
              if ((newState = 'stage2' &amp;&amp; doc.data().state = 'stage1') ||
                  (newState = 'stage3' &amp;&amp; doc.data().state = 'stage2')) {
                t.update(myDocumentRef, { population: newPopulation });
              } else {
                // Keep retrying the transaction until it succeeds
              }
          });
  }).then(result =&gt; {
      console.log('Transaction success!');
  }).catch(err =&gt; {
      console.log('Transaction failure:', err);
  });
  </code></pre>