Re: [fetch] Aborting a fetch (#27)

I've implemented a Task library to demonstrate a more elegant way of
handling cancellation than rejecting Promise chains. Tasks have nearly the
same API as a Promise, but Tasks must be run explicitly. When you run a
Task you get a subscription option you can use to stop observing the Task.
When a Task detects that it has no more observers, it can optionally cancel
any pending actions scheduled in order to resolve it.

A Promise represents the eventual value of an asynchronous unit of work,
but not the unit of work itself. A Task is an abstraction over both the
unit of work and its eventual value. That's why a Task is cancellable, and
a Promise is not.

Here's an example of a program which waits for a user to click a button and
then issues a network request to retrieve a stock quote. If the button is
clicked again while the network request is still pending, the current
network request is aborted and a new one is issued.

var outgoingRequest;function waitForQuote() {
  // if there's a request in-flight, stop observing the result
  if (outgoingRequest) {
    outgoingRequest.dispose();
    outgoingRequest = undefined;
  }

  outgoingRequest =
    Task.
      // wait for next button click...
    nextEvent(getQuoteButton, 'click').
      // return a task with the stock quote and auto-unwrap result
just like Promise's then
      when(function() {
        return getQuote('NFLX');
      }).
      // run and await the result
      run(function(val) {
        // display the price
        priceTextBox.value = val;
        outgoingRequest = undefined;

        waitForQuote();
      });
}

waitForQuote();



Check out the repo here (
https://github.com/jhusain/task-lib/blob/master/README.md). In there I
demonstrate many more usages of Task. Hopefully after reading it will
become clearer why I think choosing a more appropriate abstraction for
async tasks is preferable to bolting cancellation semantics on to a
Promise.

You can also play with a live (but stubbed) example here:
http://requirebin.com/?gist=533ad1e9d573ea7e9c5e

Later this week I'll fork the fetch polyfill to demonstrate how elegantly
Task could replace Promises in this API.

On Thu, Apr 2, 2015 at 12:22 PM, Petka Antonov <notifications@github.com>
wrote:

> @WebReflection <https://github.com/WebReflection> .cancellable is old
> api, new api doesnt have it
>
> —
> Reply to this email directly or view it on GitHub
> <https://github.com/whatwg/fetch/issues/27#issuecomment-89015617>.
>


---
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/27#issuecomment-89137845

Received on Friday, 3 April 2015 03:03:09 UTC