Idea: Bind operator and cancellation

# Jérémy Judéaux (8 years ago)

Hello,

I'd like to share an idea / experiment, trying to make asynchronous operations cancellable by using the (still in stage 0 proposal) bind operator.

My first goal was to cancel an asynchronous operation, so not just a cancellable Promise, but a whole chain of promises. Also, I wanted that the code outside of my operation, if not aware that the code may cancel, just sees a classic Promise that may reject with a "cancelled" exception. And I wanted an object to represent the state of the asynchronous operation (cancelled or not).

So I came up with a CancelToken (inspired by a lot of previous proposals and discussions I've seen). And I use an instance of that token, and the bind/pipeline operator, to write my chain of promises:

const token = new CancelToken();
asyncFoo()
  ::token.then(asyncBar)
  ::token.then(value => console.info(value))
  ::token.catch(exception => console.error(exception))
  ::token.iscancelled(() => console.debug('Operation cancelled'))
  ::token.finally(clean)

To cancel such chain, I thought to either provide a function when constructing the token, or propagate the state of another token (using listeners):

const token = new CancelToken(abort => button.onclick = abort);

const otherToken = new CancelToken(token); // token may be falsy

And there are probably a lot of ideas to derive from that:

if (token.cancelled) { /*...*/ }
token.onCancelListener(callback);
setCancellableTimeout(func, 1000, token);
// ...

I think the pipeline operator, no matter the final syntax or behaviour, can be very helpful to handle cancellation. Sorry if that’s been discussed before, I haven’t find it.

Best .

Jeremy