Promise Cancellation Is Dead — Long Live Promise Cancellation!

Option 1 - Use Bluebird

// Bluebird promise cancellation
const promise = new Promise((resolve, reject, onCancel) => {
const id = setTimeout(resolve, 1000);
onCancel(() => clearTimeout(id));
});
// use the promise as usual
promise.then(() => console.log('done'));
// anytime later
promise.cancel();

Option 2 - Use Another Promise

// a basic stitched-together CancelToken
// creation mechanism
function createToken() {
const token = {};
token.promise = new Promise(resolve => {
cancel = (reason) => {
// the reason property can be checked
// synchronously to see if you're cancelled
token.reason = reason;
resolve(reason);
});
};
return { token, cancel };
}
// create a token and a function to use later.
const { token, cancel } = createToken();
// your functions that return promises would also take
// a cancel token
function delay(ms, token) {
return new Promise(resolve => {
const id = setTimeout(resolve, ms);
token.promise.then((reason) => clearTimeout(id));
});
};

Option 3 - Use Rx Subscriptions

// create a subscription to use with your promise
const subscription = new Rx.Subscription();
const promise = new Promise(resolve => {
const id = setTimeout(resolve, 1000);
// add teardown logic to the subscription
subscription.add(() => clearTimeout(id));
});
// use the promise as usual
promise.then(() => console.log('done'));
// call unsubscribe at any point to cancel
subcscription.unsubscribe();

Option 4 - Ditch promises and just use Observables! (This author’s totally biased choice)

// create an observable, you can return teardown logic
const source$ = new Rx.Observable(observer => {
const id = setTimeout(() => observer.next(), 1000);
return () => clearTimeout(id);
};
// subscribing gives you a subscription
const sub = source$.subscribe(() => console.log('done'));
// cancel at any time later
sub.unsubscribe();

How Promise Cancellation Would Have Effected Observables

// current Observables
const subscription = someObservable$.subscribe(observer);
subscription.unsubscribe();
// with CancelToken
const { token, cancel } = CancelToken.source();
someObservable$.subscribe(observer, token);
cancel();

--

--

--

RxJS Lead. Views are my own

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ben Lesh

Ben Lesh

RxJS Lead. Views are my own

More from Medium

The Pros and Cons of Angular vs React JS

Angular Best Practices — 2022

Angular

What are Modules in Angular?

React vs Angular