Satisfying a request from a service employee

I have the following code from my service worker:

self.addEventListener('fetch', function (event) { var fetchPromise = fetch(event.request); fetchPromise.then(function () { // do something here }); event.respondWith(fetchPromise); }); 

However, it does some strange things in the dev console and seems to do asynchronously instead of a script instead of synchronous (which is bad in this context).

Is there a way to listen when a request is executed without calling fetch(event.request) manually?

For instance:

 // This doesn't work self.addEventListener('fetch', function (event) { event.request.then(function () { // do something here }); }); 
+6
source share
1 answer

If you want your entire series of actions to be completed before the response has been returned to the page, you must respond with the whole chain of promises, not just the initial promise returned with fetch.

 self.addEventListener('fetch', function(event) { event.respondWith(fetch(event.request).then(function(response) { // The fetch() is complete and response is available now. // response.ok will be true if the HTTP response code is 2xx // Make sure you return response at the end! return response; }).catch(function(error) { // This will be triggered if the initial fetch() fails, // eg due to network connectivity. Or if you throw an exception // elsewhere in your promise chain. return error; })); }); 
+3
source

All Articles