Synchronous or sequential sampling in Service Worker

I need to send a series of PUT and POST requests from Service Worker. The order in which they are sent matters.

Requirements:

  • Based on the request method, URL and JSON body, send the request
  • If it succeeds ( response.status < 300):
    • pass body function to success
    • Call the next request in the queue
  • If this fails:
    • Passing a response request Text or err to the error function
    • Stop execution

If I just iterate over the queue and call fetchfor each request, network dispersion can (often does) cause the requests to arrive at the server in order.

How to create a query chain fetchwhere each result depends on the success of the previous one?


What I tried:

  • XHR (, "async: false", Service Worker).
  • setTimeout(sendRequest, i*200). , .
  • Promise loops ES6 Promise Patterns. , , . .

. "" API , . , .

+4
2

, Promise, ?

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

function handleResponseWithQueue(queue) {
  return function handleResponse(response) {
      if (response.ok && queue.length > 0)
        return performWorkWith(queue.shift()).then(handleResponseWithQueue(queue));
  };
}

():

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

, Sync loop ES6 Promise Patterns.

"" .reduce(), .catch() . /throw .then() .catch() .

, , , HTTP- fetch(...).then(...) throw, , HTTP- a .catch(). (NetworkError .catch(), .) - :

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

Source: https://habr.com/ru/post/1606429/


All Articles