Created
December 18, 2013 15:13
-
-
Save juandopazo/8023929 to your computer and use it in GitHub Desktop.
CancellablePromise implementation
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
| YUI.add('cancellable-promise', function (Y) { | |
| function CancellationError(message) { | |
| CancellationError.superclass.constructor.apply(this, arguments); | |
| this.message = message; | |
| } | |
| Y.extend(CancellationError, Error, { | |
| name: 'cancel' | |
| }); | |
| function CancellablePromise(resolver, onCancel) { | |
| CancellablePromise.superclass.constructor.call(this, resolver); | |
| var resolver = this._resolver; | |
| this._onCancel = function () { | |
| if (resolver._status === 'pending') { | |
| try { | |
| onCancel(); | |
| } catch (e) { | |
| resolver.reject(e); | |
| return; | |
| } | |
| resolver.reject(new CancellationError()); | |
| } | |
| }; | |
| } | |
| Y.extend(CancellablePromise, Y.Promise, { | |
| then: function () { | |
| var self = this, | |
| promise = CancellablePromise.superclass.then.apply(this, arguments); | |
| promise._onCancel = function () { | |
| self._onCancel.call(); | |
| }; | |
| return promise; | |
| }, | |
| cancel: function () { | |
| this._onCancel.call(); | |
| } | |
| }); | |
| Y.CancellablePromise = CancellablePromise; | |
| }, '@VERSION@', { | |
| requires: [ | |
| 'promise', | |
| 'oop' | |
| ] | |
| }); |
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
| YUI().use('cancellable-promise', function (Y) { | |
| function wait(ms) { | |
| var timer; | |
| return new Y.CancellablePromise(function (resolve) { | |
| timer = setTimeout(function () { | |
| resolve(ms); | |
| }, ms); | |
| }, function () { | |
| console.log('cancelling...'); | |
| clearTimeout(timer); | |
| }); | |
| } | |
| wait(5000).then(function (ms) { | |
| console.log('fulfilled'); | |
| console.log(ms); | |
| }, function (err) { | |
| console.log('rejected'); | |
| console.log(err); | |
| }).cancel(); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment