Skip to content

Instantly share code, notes, and snippets.

@eduardolundgren
Created March 25, 2014 20:51
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 eduardolundgren/9771032 to your computer and use it in GitHub Desktop.
Save eduardolundgren/9771032 to your computer and use it in GitHub Desktop.
Y.CancellablePromise
/**
* Error used as a rejection reason for canceled Promises.
*
* @class Promise.CancellationError
* @constructor
* @extends {Error}
* @param {String} opt_message An optional debugging message for describing the
* cancellation reason.
*/
function CancellationError(opt_message) {
CancellationError.superclass.constructor.apply(this, arguments);
this.message = opt_message;
}
A.extend(CancellationError, Error, {
name: 'cancel'
});
A.Promise.CancellationError = CancellationError;
/**
* Cancellable promise.
*
* @class CancellablePromise
* @constructor
* @extends {Promise}
* @param {Function} fn A function where to insert the logic that resolves this
* promise. Receives `fulfill` and `reject` functions as parameters. This
* function is called synchronously.
*/
function CancellablePromise() {
CancellablePromise.superclass.constructor.apply(this, arguments);
}
A.extend(CancellablePromise, A.Promise, {
then: function() {
var instance = this,
promise = CancellablePromise.superclass.then.apply(this, arguments);
promise.cancel = A.bind(instance.cancel, instance);
return promise;
},
cancel: function(opt_message) {
this._resolver.reject(new A.Promise.CancellationError(opt_message));
}
});
A.CancellablePromise = CancellablePromise;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment