Cancellable Promises
The concept of this kind of cancellable promises was developed for internal usage to make certain things work. The only difference between a native promise and cancellable promise from a client code view is a .cancel
method which can be used to reject a promise from the outside world. It still can be passed to native promise methods like Promise.all, Promise.race
, etc.
Example usage
import { createCancellablePromise } from 'csp-coffee/cancellablePromise'
const { cancellablePromise, resolve, reject } = createCancellablePromise(() => {
console.log('Do something when promise is cancelled');
})
createCancellablePromise
function accepts an onCancel
callback which is called when promise is cancelled. It returns an object with our cancellablePromise
and two methods: resolve
and reject
. resolve
and reject
act exactly like a resolve
and reject
inside a promise constructor and provide a way to control a promise from the outside. Value inside of a cancellablePromise
property contains our promise with a .cancel
method.
Cancelling the promise
cancel: (reason?: any) => Promise<void>
.cancel
accepts any value as an argument and this is a value the onCancel
callback will be called with. It returns a promise which resolves once cancellation is done
import { createCancellablePromise } from 'csp-coffee/cancellablePromise'
const { cancellablePromise, resolve, reject } = createCancellablePromise((message: string) => {
console.log(message);
});
cancellablePromise.cancel('I AM CANCELLED')
// Will log 'I AM CANCELLED' to the console
Last updated