Offer an imperative API on top of promise, with cancellation support
npm install --save awesome-imperative-promise// oryarn add awesome-imperative-promise
- Imperative methods to trigger promise resolve/reject
- Imperative method to trigger promise cancellation (the promise will never resolve/reject)
- Can wrap an existing promise or simply create a new one
- Typescript native support
;const wrappedPromise = ;// Wrap an existing promise and expose some additional imperative methods// The existingPromise paramter is optional and the returned promise with resolve/reject when the existing promise doconst promise resolve reject cancel = ;// will make the returned promise resolved (not the wrapped one);// will make the returned promise reject (not the wrapped one);// will ensure the returned promise never resolves or reject;
The returned promise can only resolve/reject/cancel once and will ignore further imperative calls like regular promises do.
If you call
cancel() and then call
resolve("val") (or if the wrapped promise resolves), the returned promise will never resolve because it has been cancelled first.
I find this useful to be able to cancel the resolution of promises, and use this lib as an implementation detail in other libs I build, like awesome-debounce-promise.
This is particularly useful in React apps where you want to ensure an async process is cancelled when component unmounts, to avoid triggering a setState and get a warning. See isMounted() is an antipattern
MIT © slorber