Created
April 4, 2016 00:03
-
-
Save roiavidan/de6164d3e9b9946ce4f88129a82ea69e to your computer and use it in GitHub Desktop.
Simple Cancelable 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
/* | |
* 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