title: Synchronous or Sequential fetch in Service Worker
body: <p>I need to send a series of PUT &amp; POST requests from a Service Worker. The order in which they're sent matters.</p>
  
  <p>Requirements:</p>
  
  <ul>
  <li>Given a request method, url, and JSON body, send the request</li>
  <li>If it succeeds (<code>response.status &lt; 300</code>):
  
  <ul>
  <li>Pass body to a success function</li>
  <li>Call next request in queue</li>
  </ul></li>
  <li>If it fails:
  
  <ul>
  <li>Pass responseText or err to error function</li>
  <li>Stop execution</li>
  </ul></li>
  </ul>
  
  <p>If I simply iterate through the queue and call <code>fetch</code> for each request, network variance can (often does) cause the requests to arrive at the server out of order.</p>
  
  <p>How do I make a chain of <code>fetch</code> requests, where each result depends on the success of the previous one?</p>
  
  <hr>
  
  <p>What I've tried:</p>
  
  <ul>
  <li>XHR instead (assuming I could use "async: false", but this is not allowed in Service Worker).</li>
  <li><code>setTimeout(sendRequest, i*200)</code>. A hack, not reliable.</li>
  <li><code>Promise loops</code> based off of these examples <a href="https://github.com/DukeyToo/es6-promise-patterns" rel="nofollow">ES6 Promise Patterns</a>. This seemed most promising, but the examples are for a simple case where success is assumed. Can't get it to work with fetch.</li>
  </ul>
  
  <p><strong>Context</strong>: I'm using an "outbox" of API requests to support offline reading, creating, and updating of data. Works well, except for this ordering issue.</p>