Last active
September 2, 2015 03:57
-
-
Save nqbao/e9cc34d3a2bb07eed505 to your computer and use it in GitHub Desktop.
cancelable promise prototype
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
function cancellablePromise(executor) { | |
var deferred = Promise.defer(); | |
var cancelled = false; | |
var promise = new Promise(executor).then(function(result) { | |
if (!cancelled) deferred.resolve(); | |
else return arguments[0] | |
}); | |
var actualPromise = Promise.all(deferred.promise, promise) | |
.then(function(result) { | |
return result.pop(); // return the actual result | |
}) | |
return { | |
cancel: function(reason) { | |
cancelled = true; | |
if (reason) { | |
deferred.reject(new Error(reason)) | |
} | |
}, | |
promise: actualPromise, | |
then: actualPromise.then.bind(actualPromise) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment