Hacker News new | past | comments | ask | show | jobs | submit login

> A C#-style cancellation token API, orthogonal to promises, is simple, easy to build, and easy to understand.

I'm interested in learning more about this, do you happen to have any links to building such an api?




Creating a cancel token gives you two things: a token and a function. You call the function when the token should be cancelled, and the token can tell you when it has been cancelled. The simplest way to query the token is to call token.throwIfRequested(), which throws a Cancel if the token is cancelled. The token can also give you promises or callbacks of cancellation if you like, so you can do stuff like `const result = await Promise.race(token.promise, promiseOfResult);`

So you pass the token into a cancellable API, and that API calls token.throwIfRequested() in places where it is safe for it to do so (i.e. outside of critical sections).

A library implementing this in <100 lines of code (based on a spec that has since been sadly abandoned): https://www.npmjs.com/package/cancel-token


Oh I like this. It's pretty simple, both code and conceptually, that it seems obvious in retrospect.

It allows a function to be cancelled from the outside, but only on its own terms, and gives the function a chance to clean up after itself.

I'm going to use this




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: