tc39 / proposal-cancellation

Proposal for a Cancellation API for ECMAScript
https://tc39.github.io/proposal-cancellation
BSD 3-Clause "New" or "Revised" License
266 stars 12 forks source link

How the separation of CancellationToken and CancellationTokenSource is useful? #8

Closed falsandtru closed 7 years ago

falsandtru commented 7 years ago

Seems like that separation make no restriction. Everyone can cancel any token. Another, should I post the comment to the mailing list in place of here?

rbuckton commented 7 years ago

I'm not sure I understand what you mean. Only the CancellationTokenSource can cancel its token. You do not pass the CancellationTokenSource to a callee, just the token. For example:

const source = new CancellationTokenSource();
otherAsyncFn(source.token); // receives the token, does not have access to the source.
source.cancel(); // only the source can cancel
falsandtru commented 7 years ago

Sorry, I thought the following code output 0, 1, 2, but it actually outputs 1, 2. It has no problem I thought. Thanks for the response!

const token = new CancellationToken();
const source = new CancellationTokenSource([token]);
token.register(() => console.log(0));
source.token.register(() => console.log(1));
new CancellationTokenSource([source.token]).token.register(() => console.log(2));
source.cancel();