Re: [ServiceWorker] Allow respondWith() to be called asynchronously or allow some way to cancel the response. (#836)

I'm beginning to agree with @domenic that this particular use case really should just be handled by a middleware layer rather than trying to somehow provide APIs that allow this. Blocking respondWith would be really weird (and it couldn't really be blocking anyway, that's just not how javascript works; it could return a promise and reject that promise later of course, but I don't think allowing multiple respondWith calls in such a ways is really something we would want to do.

If you really want to make this work, you can sort of do this today already like this:
```js
function cancelResponse(event) {
  var newEvent = new FetchEvent("fetch",
      {request: event.request, clientId: event.clientId, isReload: event.isReload});
  newEvent.shouldIgnore = true;
  var resolver
  console.log("Cancelling response");
  var promise = new Promise(resolve => {
    newEvent.respondWith = function(response) {
      console.log("Called respondWith");
      resolve(response);
    };
  });
  self.dispatchEvent(newEvent);
  return promise;
}

self.addEventListener('fetch', event => {
  if (event.shouldIgnore) return;
  console.log('Inside the base handler');
  event.respondWith(new Promise(resolve => {
      setTimeout(() => resolve(cancelResponse(event)), 1000);
    }));
});
```



---
Reply to this email directly or view it on GitHub:
https://github.com/slightlyoff/ServiceWorker/issues/836#issuecomment-186402968

Received on Friday, 19 February 2016 20:56:11 UTC