Last active
August 29, 2015 14:00
-
-
Save bterlson/03cbf2ab02f7e3640ba9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.