Last active
March 31, 2016 17:17
-
-
Save andyedinborough/61d4982a355421d2585b to your computer and use it in GitHub Desktop.
This file contains 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
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