Skip to content Skip to sidebar Skip to footer

Synchronous Or Sequential Fetch In Service Worker

I need to send a series of PUT & POST requests from a Service Worker. The order in which they're sent matters. Requirements: Given a request method, url, and JSON body, send t

Solution 1:

Instead of turning each request in the queue into a Promise right away, why not just pop entries off the queue as you need them?

var workQueue = [work, goes, here];
var currentItem = workQueue.shift();
returnperformWorkWith(currentItem)
         .then(handleResponseWithQueue(workQueue));

functionhandleResponseWithQueue(queue) {
  returnfunctionhandleResponse(response) {
      if (response.ok && queue.length > 0)
        returnperformWorkWith(queue.shift()).then(handleResponseWithQueue(queue));
  };
}

You can generalize this pattern to (simplified):

function series(work, queue) {
  if (queue.length <= 0) return;
  work(queue.shift()).then(function() {
    if (queue.length > 0) return series(work, queue);
  });
}

Solution 2:

I think you're going to want to follow the Sync loop pattern from that ES6 Promise Patterns page.

Once your "success" promise chain is set up via .reduce(), you can attach a single .catch() clause to the end to handle the error reporting. Any promise rejection/throw inside of the promise chain will short-circuit all of the .then()s and jump straight to your .catch() at the end.

In order for this to work as you describe, you'll want to explicitly check for an error HTTP response status in your fetch(...).then(...) and throw if you encounter one, since a HTTP error response won't otherwise trigger a .catch(). (NetworkErrors or similar runtime exceptions will trigger the .catch(), though.) Something like:

fetch('https://example.com').then(response => {
  if (!response.ok) { // See https://fetch.spec.whatwg.org/#ok-statusthrownewError('Invalid HTTP response: ' + response.status);
  }
  // Otherwise, do something with the valid response.
})

Post a Comment for "Synchronous Or Sequential Fetch In Service Worker"