@kmdavis/cancelable-promise v0.1.2
Cancelable Promise
Promise-like class that adds cancelability to ES6 Promises.
A CancelablePromise is a Promise that can be canceled so that the onResolved & onRejected callbacks don't get called. Can be used to cancel async operations that are no longer relevant (e.g. a fetch initiated by a React component that has since been unmounted).
Installation
npm install @kmdavis/cancelable-promiseUsage
import CancelablePromise from "@kmdavis/cancelable-promise";
const myPromise = new CancelablePromise((resolve) => {
// This Promise will automatically resolve in 5 seconds...
// ...unless it gets canceled first!
setTimeout(() => {
console.log("Gonna try to resolve");
resolve();
}, 5000);
});
setTimeout(
// Cancel the Promise
() => {
console.log("Gonna try to cancel");
myPromise.cancel()
},
// At some random point between 4 and 6 seconds
Math.floor(Math.random() * 2000) + 4000
);
myPromise.then(
() => console.log("myPromise was resolved"),
() => console.log("myPromise was rejected"),
() => console.log("myPromise was canceled")
);
// Who do you think will win?In addition to all of the public methods of an ES6 Promise (then, catch, finally, resolve, reject, try, all, & race) a CancelablePromise extends then and all and also has cancel, canceled, isCanceled, isResolved, & isRejected
then (onResolved, onRejected, onCanceled) : CancelablePromise
Attaches callbacks for the resolution, rejection and/or cancelation of the CancelablePromise.
static all (listOfPromises) : CancelablePromise
Creates a CancelablePromise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected, or canceled when any CancelablePromise is canceled.
cancel () : void
Cancel a CancelablePromise.
static cancel (promise) : void
Cancel a CancelablePromise.
canceled (onCanceled) : CancelablePromise
Attaches a callback for the cancelation of the CancelablePromise.
isCanceled () : bool
Is the CancelablePromise canceled?
isResolved () : bool
Is the CancelablePromise resolved?
isRejected () : bool
Is the CancelablePromise rejected?
Development setup
npm install
npm testRelease History
- 0.1.0
- Initial public release
Meta
Kevan Davis kevan.davis@me.com
Distributed under the BSD license.
https://github.com/kmdavis/cancelable-promise
Contributing
- Fork it (https://github.com/kmdavis/cancelable-promise/fork)
- Create your feature branch (
git checkout -b feature/fooBar) - Commit your changes (
git commit -am 'Add some fooBar') - Push to the branch (
git push origin feature/fooBar) - Create a new Pull Request