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)); } }