Skip to content

A simpler idea? #6

@domenic

Description

@domenic

Inspired by #1 (comment), what about something as simple as this? Assume underscored properties are "actually private," i.e. wouldn't be specced and are only here to illustrate. Using ES6 for brevity.

class CancellablePromise extends Promise {
  constructor(resolver, onCancelled) {
    this._onCancelled = onCancelled;
    this._isResolved = false;
    super((resolve, reject) => {
      this._reject = reject;
      const wrappedResolve = value => { resolve(value); this._isResolved = true; };
      const wrappedReject = reason => { reject(reason); this._isResolved = true; };
      resolver(wrappedResolve, wrappedReject);
    });
  }

  cancel() {
    if (typeof this._onCancelled === "function" && !this._isResolved) {
      try {
        this._onCancelled();
      } catch (e) {
        this._reject(e);
      }
    }

    this._reject(new Cancellation()); // I assume double-rejections are no-ops
  }

  then(...args) {
    // When you chain off a cancellable promise, you get another cancellable promise.
    // And cancellations propagate to progenitor promises, i.e. when calling
    // `promise.then(...).cancel()`, this ends up calling `promise.cancel()` too (see examples).
    return new this.constructor(
      (resolve, reject) => super.then(resolve, reject),
      () => this.cancel()
    );
  }

  // Allow removing cancellation privileges, for handing out to untrusted consumers. 
  uncancellable() {
    return super.then();
  }
}

// A cancellable XHR.
function get(url) {
  const xhr = new XMLHttpRequest();
  return new CancellablePromise(
    (resolve, reject) => {
      xhr.open("GET", url, true);
      xhr.onload = () => resolve(request.responseText);
      xhr.onerror = () => reject(new Error("Can't XHR"));
      xhr.send();
    },
    () => xhr.abort()
  );
}

// A cancellable JSON-parsing XHR, using cancellation propagation.
function getJSON(url) {
  return get(url).then(JSON.parse);
}

getJSON("http://example.com/data.json").cancel();
// => should work, calling the original promise's `cancel`, and thus
// the `onCancelled` passed in to the constructor, and thus `xhr.abort`.

get("http://example.com/data.json").uncancellable().cancel();
// => throws, no `cancel` method

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions