Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created December 18, 2013 15:13
Show Gist options
  • Select an option

  • Save juandopazo/8023929 to your computer and use it in GitHub Desktop.

Select an option

Save juandopazo/8023929 to your computer and use it in GitHub Desktop.
CancellablePromise implementation
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'
]
});
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