Make your promises cancelable
NPM:
npm install make-cancel-promise
- Working with native, polyfills, shim'ed Promises
- Isomorphic library
- Zero dependencies
- Typescript declarations
Basic usage
import {
makeCancelPromise,
CancelablePromiseError,
cancelPromise
} from 'make-cancel-promise';
const cancelablePromise = makeCancelPromise(
(resolve, reject, onCancel) => {
const timeoutResolve = setTimeout(() => {
resolve('resolve');
}, 10);
const timeoutReject = setTimeout(() => {
reject('reject');
}, 20);
onCancel(() => {
clearTimeout(timeoutResolve);
clearTimeout(timeoutReject);
});
});
cancelablePromise.catch((e) => {
if(e instanceof CancelablePromiseError){
console.log('Promise has been canceled');
}
});
cancelPromise(cancelablePromise).catch((e) => {
console.error(e);
});
Cancel with ClearSymbol
import {
makeCancelPromise,
CancelablePromiseError,
clearSymbol
} from 'make-cancel-promise';
const cancelablePromise = makeCancelPromise(
(resolve, reject, onCancel) => {
const timeoutResolve = setTimeout(() => {
resolve('resolve');
}, 10);
const timeoutReject = setTimeout(() => {
reject('reject');
}, 20);
onCancel(async () => {
clearTimeout(timeoutResolve);
clearTimeout(timeoutReject);
});
});
cancelablePromise.catch((e) => {
if(e instanceof CancelablePromiseError){
console.log('Promise has been canceled');
}
});
cancelablePromise[clearSymbol]().catch((e) => {
console.error(e);
});
Cancel with ClearSymbol without rejecting (using in some of cases)
Warning: You must resolve or reject promise in onCancel callback manually to prevent a pending promises in memory
import {
makeCancelPromise,
CancelablePromiseError,
clearSymbol
} from 'make-cancel-promise';
const cancelablePromise = makeCancelPromise(
(resolve, reject, onCancel) => {
const timeoutResolve = setTimeout(() => {
resolve('resolve');
}, 10);
const timeoutReject = setTimeout(() => {
reject('reject');
}, 20);
onCancel(async () => {
clearTimeout(timeoutResolve);
clearTimeout(timeoutReject);
// or resolve
reject(new CancelablePromiseError('Error'));
});
});
cancelablePromise.catch((e) => {
if(e instanceof CancelablePromiseError){
console.log('Promise has been canceled');
}
});
// passing false to "clearSymbol" function will be cancel promise without rejecting
cancelablePromise[clearSymbol](false).catch((e) => {
console.error(e);
});