Re: [whatwg/fetch] Aborting a fetch: The Next Generation (#447)

I agree with @annevk that having a representation of an ongoing fetch is the least hacky way to do this. However, I don't like the way you end up passing the controller out of the function that creates it, feels hacky.

```js
// ew
let controller;
fetch(url, {
  control(c) {
    controller = c;
  }
});
```

This brings me back to "Add a method to the returned promise". We could make `fetch()` return a controller object that is also thennable. Its then/catch methods would proxy to an underlying promise, [like this](http://jsbin.com/zopaya/edit?js,console).

```js
const controller = fetch(url);
controller.then(response => …);
controller.abort();
```

Something like `controller.observer` could contain the "read-only" parts of the controller. This is where we could provide upload progress, changes to priority etc. You could safely pass this to other pieces of code allowing them to observe the fetch but not modify it.

```js
const controller = fetch(url);
// Hand waving through the API a bit…
controller.observer.complete; // a promise that resolves, or rejects with a TypeError (network error) or AbortError (cancelled)
controller.observer.uploadProgress.subscribe(…);
controller.observer.priorityChange.subscribe(…);
```

This could also appear on the `fetchEvent`, solving the service worker case:

```js
addEventListener('fetch', event => {
  const catFetch = fetch('cat.jpg');
  event.fetchObserver.complete.catch(err => {
    if (err.name == 'AbortError') catFetch.abort();
  });

  event.respondWith(catFetch);
});
```

**Cons:**

This is a pretty big change. We'd be returning an object that wasn't `instanceof Promise`. Also, one of the points of contention in the previous thread was allowing someone you gave the promise to to affect the outcome of the promise (eg, aborting it). Whoever you pass the promise to can already get a lock on & drain the response stream, so it isn't really immutable. If you're passing a fetch promise to multiple people and expecting them to all be able to independently handle the response… you're going to have a bad time.

If this becomes a blocker, the return type could switch on `fetch(url, {controllable: true})`, which is a little hacky, but IMO less hacky than the callback.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/447#issuecomment-270628740

Received on Thursday, 5 January 2017 12:00:25 UTC