gitmyhub

CAF

JavaScript ★ 1.4k updated 3y ago

Cancelable Async Flows (CAF)

A JavaScript library that wraps generator functions so async code can be cancelled cleanly from outside, using a shareable cancellation token.

JavaScriptNode.jsnpmAbortControllersetup: easycomplexity 3/5

CAF, short for Cancelable Async Flows, is a JavaScript library that lets you write asynchronous code in a style that looks almost synchronous, while adding the ability to cancel it from outside. Asynchronous code is code that waits for something, like a network request, without freezing the rest of the program. JavaScript already has built-in ways to write async code, but canceling it partway through has historically been awkward.

This library wraps a particular type of JavaScript function called a generator, making it behave like a modern async function. The key addition is a cancellation token: you create one before starting an operation, pass it in, and if you later decide to cancel, you call the abort method on the token. The wrapped function then stops immediately, even if it was mid-way through waiting on something.

One useful aspect is that the cancellation can chain across multiple functions. If function A calls function B which calls function C, and all three share the same cancellation token, canceling once stops all three at whatever point they had reached.

The library also includes a companion called CAG for generators that produce a stream of values asynchronously, not just a single result.

CAF is a pure JavaScript utility, published to npm, and works in Node.js and browser environments that support ES2018 features. Older environments can use it after running the code through a transpiler. The README is detailed and covers many usage patterns and edge cases. The full README is longer than what was shown.

Where it fits