Created
December 20, 2016 22:08
-
-
Save dwickern/01e369bce5d14a0bb3354d4819495ffb to your computer and use it in GitHub Desktop.
Ember cancellable promise
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
import Ember from 'ember'; | |
export class CancellablePromise extends Ember.RSVP.Promise { | |
constructor(resolver, cancel, label) { | |
super(function (resolve, reject) { | |
try { | |
resolver(function resolved(value) { | |
cleanup(); | |
resolve(value); | |
}, function rejected(reason) { | |
cleanup(); | |
reject(reason); | |
}); | |
} catch (e) { | |
cleanup(); | |
reject(e); | |
} | |
}, label); | |
function cleanup() { | |
delete self._cancel; | |
} | |
let self = this; | |
this._cancel = cancel; | |
} | |
cancel() { | |
if (this._cancel) { | |
this._cancel(); | |
delete this._cancel; | |
} | |
} | |
then() { | |
let parent = this; | |
let child = super.then(...arguments); | |
// cancellation travels upstream to parent promises | |
child._cancel = () => parent.cancel(); | |
return child; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment