Skip to content

Instantly share code, notes, and snippets.

@andyedinborough
Last active March 31, 2016 17:17
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 andyedinborough/61d4982a355421d2585b to your computer and use it in GitHub Desktop.
Save andyedinborough/61d4982a355421d2585b to your computer and use it in GitHub Desktop.
const noop = () => {};
export default class CancellablePromise {
constructor(executorOrPromise){
this._promise = new Promise((resolve, reject) => {
let promise = executorOrPromise;
if(!promise.then) promise = new Promise(executorOrPromise);
promise.then((...args) => {
if(this.cancelled) reject('cancelled', ...args);
else resolve(...args);
});
promise.catch(reject);
});
}
cancel() {
this.cancelled = true;
this.catch(noop);
return this;
}
then(func) {
return new CancellablePromise(this._promise.then(func));
}
catch(func) {
return new CancellablePromise(this._promise.catch(func));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment