Skip to content

Instantly share code, notes, and snippets.

@roiavidan
Created April 4, 2016 00:03
Show Gist options
  • Save roiavidan/de6164d3e9b9946ce4f88129a82ea69e to your computer and use it in GitHub Desktop.
Save roiavidan/de6164d3e9b9946ce4f88129a82ea69e to your computer and use it in GitHub Desktop.
Simple Cancelable Promise
/*
* A Promise which can be "cancelled".
* This is not related to https://github.com/promises-aplus/cancellation-spec/issues.
*
* I just needed some mechanism to force-reject an on-going promise, and possibly execute a callback on cancellation.
* Hope this example helps someone!
*/
function CancelablePromise(executor, onCancel) {
var cancelFunc;
var cancelable = new Promise(function(resolve, reject) {
cancelFunc = reject;
});
var instance = Promise.race([new Promise(executor), cancelable]);
instance.cancel = function() {
cancelFunc();
typeof onCancel === 'function' && onCancel();
};
return instance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment