[w3c/ServiceWorker] provide a way to execute work after browser has consumed a response (#1397)

Recently I've been looking at some code that does something like this:

```javascript
addEventListener('fetch', evt => {
  evt.respondWith(async function() {
    let response = await fancyResponseLoader(evt.request);
    doCompletionWork(response);
    return response;
  }());
});
```

After it has a Response it does some amount of completion work.  This could book keeping, recording metrics, opportunistic caching, etc.

What I have seen in these cases is that the completion work ends up delaying the browser from processing the response.

It might be nice to provide some way for the code to execute something after the browser has processed the response.  A couple options:

  * Make `respondWith()` return a promise for once it has completed its work on the service worker thread.
  * Add a `FetchEvent.complete` promise for once it has completed its work on the SW thread.  This could also support fallback cases where respondWith() is not called at all.

With something like this we would rewrite the example above as:

```javascript
addEventListener('fetch', evt => {
  evt.respondWith(async function() {
    let response = await fancyResponseLoader(evt.request);
    evt.waitUntil(evt.complete.then(_ => doCompletionWork(response)));
    return response;
  }());
});
```

The work around for this issue is to try to use a microtask or task to get your completion work to execute after the browser is done.  This is pretty much guesswork, though, since I don't think we clearly define how browsers process the response on the SW thread.  For example, in chrome we end up internally queuing a microtask after the respondWith promise completes.  So if you want to run your completion work after you need two microtasks to get behind the browser.  And of course other browsers might be different.  Providing an explicit API would avoid this sort of confusion.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1397

Received on Thursday, 28 March 2019 17:40:30 UTC