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 the request
- If it succeeds (
response.status < 300
):- Pass body to a success function
- Call next request in queue
- If it fails:
- Pass responseText or err to error function
- Stop execution
If I simply iterate through the queue and call fetch
for each request, network variance can (often does) cause the requests to arrive at the server out of order.
How do I make a chain of fetch
requests, where each result depends on the success of the previous one?
What I've tried:
- XHR instead (assuming I could use "async: false", but this is not allowed in Service Worker).
setTimeout(sendRequest, i*200)
. A hack, not reliable.Promise loops
based off of these examples ES6 Promise Patterns. This seemed most promising, but the examples are for a simple case where success is assumed. Can't get it to work with fetch.
Context: I'm using an "outbox" of API requests to support offline reading, creating, and updating of data. Works well, except for this ordering issue.