Skip to content

Instantly share code, notes, and snippets.

@bterlson
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bterlson/03cbf2ab02f7e3640ba9 to your computer and use it in GitHub Desktop.
Save bterlson/03cbf2ab02f7e3640ba9 to your computer and use it in GitHub Desktop.
class Cancellation extends Error { };
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(cb,eb, ...rest) {
return new this.constructor((res, rej) => {
super(
(...args) => res(cb(...args)),
(...args) => rej(eb(...args)),
...rest
);
}, () => this.cancel())
}
uncancellable() {
return super.then();
}
}
@xirzec
Copy link

xirzec commented Apr 30, 2014

then() code looks a bit terse in its variable names. I would expand those.

Otherwise seems good to me, though I'm not familiar enough with Promise implementations to validate your constructor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment