Skip to content

Latest commit

 

History

History

canc-coroutine

README.md

canc ⮿ A crafty foundation for cancelable promises
 

@cancjs/coroutine

Cancelable generator-based drop-in replacements for async/await and async iterators.


Introduction

An async function cannot be stopped from the outside. Its promise is created and driven by the engine, and nothing in the language lets a caller interrupt the function between two await points.

This package brings that control back. A generator function wrapped with canc.async returns a CancelablePromise, and every step written as yield* canc.await(...) is a point where cancellation can take effect. The code keeps the shape of an async function, with yield* where await used to be.

cancGen.async, in the mirror namespace, does the same for async function*. The toolbox provides adapters for wrapping existing APIs, and decorators bring coroutines to class methods. See the repository for the full ecosystem.

Features

  • direct replacements for async functions and async generators
  • cancellation reaches into a running coroutine, not just into the promise it returned
  • full type inference through yield*, no casts and no any steps
  • combinator helpers (all, race, any, allSettled, try) that preserve tuple types
  • for await style consumption with per-item cancellation
  • works as a class method, with or without decorators

Getting Started

Installation

npm install @cancjs/coroutine @cancjs/promise

@cancjs/promise is a peer dependency. This package is core tier: it never removes a public name outside a major release, so the default caret pin, ^1, never loses something you call. A core minor can still fix behavior that was wrong; when a fix can break working code, the changelog entry for that minor opens with a **Breaking:** note. See Versioning for the full policy.

Usage

import * as canc from '@cancjs/coroutine';

const loadInvoice = canc.async(function* (invoiceId: string) {
  const invoice = yield* canc.await(fetchInvoice(invoiceId));
  const customer = yield* canc.await(fetchCustomer(invoice.customerId));

  return { invoice, customer };
});

const pending = loadInvoice('inv-2041');

// Rejects the coroutine with a CancelError at its current step. The customer
// request is aborted if it is already in flight, and never starts otherwise.
pending.cancel();

Independent steps run together and cancel together:

const loadDashboard = canc.async(function* () {
  const [invoices, payments] = yield* canc.await.all([
    fetchInvoices(),
    fetchPayments()
  ]);

  return summarize(invoices, payments);
});

The flat names are exported next to the namespace aliases, so this is the same code:

import { cancAsync, cancAwait } from '@cancjs/coroutine';

const loadInvoice = cancAsync(function* (invoiceId: string) {
  return yield* cancAwait(fetchInvoice(invoiceId));
});

How It Works

Where this comes from

Before async/await was standardized, libraries like co already wrote asynchronous code in direct style: a generator yields a promise, a driver awaits it and resumes the generator with the result. TC39 standardized this exact pattern as async/await in ES2017. An async function compiles to a generator state machine with a built-in promise driver, the same architecture that co used, but hidden inside the engine and hardcoded to native Promise.

Hiding the driver is what removes cancellation. Nobody outside the function holds the handle that decides whether the next step should run at all. This package puts the driver back in userland. The cost is a yield* per step. The gain is interruption at every one of them, with type inference that co never had, combinator helpers that mirror Promise.all/race/any, and async generator support for producing cancelable streams. The rest stays as close to native semantics as possible: return, throw, try/finally and delegation to other generators all work the way they do in an async function.

What cancel does

Canceling the returned promise stops the coroutine at its current step. The step's promise is canceled, the CancelError is thrown back into the generator at the point where it is suspended, and the code after that point does not run.

A canceled coroutine rejects with CancelError. Without a handler, this triggers unhandledRejection. Use @cancjs/unhandled-rejection at app entry or handle cancellation explicitly with catchCancel/suppressCancel.

Because the error is thrown into the generator, try/catch and try/finally behave the way they do in an async function. A finally block still runs on cancellation, and the steps it runs after the cancel are shielded, so cleanup cannot be canceled halfway.

The coroutine cannot tell whether a step sits inside a finally, though. When the try block returns or throws on its own, the finally runs as ordinary code, and a cancel arriving during its cleanup step would interrupt it. Shield your cleanup to cover that case:

const checkout = canc.async(function* (orderId: string) {
  const reservation = yield* canc.await(reserveStock(orderId));

  try {
    return yield* canc.await(chargeCard(orderId));
  } finally {
    yield* canc.await(CancelablePromise.resolve(releaseReservation(reservation.id), { shield: true }));
  }
});

A cancel that lands while a shielded step runs waits for that step. The body then resumes with the step's result and the cancel takes effect at the next step that is not shielded. If the body returns first, the coroutine still settles as canceled; if it throws first, it rejects with that error. The same rule applies to cancGen.async bodies.

A coroutine stays pending while those finally steps run. Right after cancel() its canceled flag is still false; it turns true when the cleanup is done and the promise rejects. Cancel handlers run at that point too, and they receive the reason passed to cancel(), not the CancelError.

In async mode, cancel() waits for the drain and returns the coroutine's own cancel handler results in registration order. Each record is fulfilled with the handler's value or rejected with its error. If no handlers ran, including when the drain threw before reaching them, the result is an empty array. The coroutine's rejection is separate. With asyncCancel: false, cancel() returns undefined immediately.

When the canceled step awaits another coroutine or a CancelablePromise, the body's finally runs only after that step's own cleanup has finished, so the inner levels of a nest clean up before the levels that await them. The wait relies on the step's cancel() returning a cleanup promise, which is the default; for a step created with asyncCancel: false the body unwinds without waiting.

A cancel unwinds the body through yield* delegation too. The forAwait, forAwait.toArray and cancGen.delegate helpers, and a generator callback passed to forAwait, run their cleanup and then keep unwinding, so the code after the helper call never runs. A generator of your own behaves differently when its finally awaits something. JavaScript resumes the caller once that finally completes, as if the delegated call had returned normally, so the statements after your yield* run (their steps are shielded, and the coroutine still settles as canceled). Check the signal you passed in the options after such a call, if (signal.aborted) return;, or keep awaits out of the helper's finally.

If the signal passed in the options is already aborted, the coroutine is canceled from the start and its body never runs. With strict, calling it returns a rejected promise instead of throwing.

Why yield* and not yield

At runtime yield promise and yield* canc.await(promise) do the same thing. The difference is typing. A bare yield is typed by the generator-wide next type, which TypeScript cannot narrow per step, so the resumed value comes back as unknown. In addition, under TypeScript strict mode, an unannotated generator cannot bare-yield without an AsyncResult return-type annotation, and a generator annotated with declared failures cannot bare-yield a promise at all.

canc.await(promise) returns a one-shot generator whose return type carries Awaited<T>, and yield* delegation reads that type back. The starred form is the one to write.

The distinction also keeps the two yield roles separate. In the async generator namespace (cancGen.async), a bare yield emits a value to the consumer, just as it does in a native async function*. Using yield* for awaiting preserves that: yield means emit, yield* means await. The same rule applies in the regular namespace for consistency.

The combinator helpers exist as canc.await.all and friends rather than plain statics for the same reason: they reconstruct tuple inference across the delegation.

Description

Two namespaces

Both namespaces are the same runtime machinery with different mental models, and each has its own entry point:

import * as canc from '@cancjs/coroutine'; // async/await world
import * as cancGen from '@cancjs/coroutine/gen'; // async function* world

In a canc.async body a bare yield is an await. In a cancGen.async body a bare yield emits a value to the consumer, and awaiting is always written yield* cancGen.await(...). Mixing helpers from one namespace into a body of the other produces wrong values silently, so keep a body in one dialect.

Both namespaces mirror native JavaScript syntax:

Native Syntax @cancjs/coroutine (canc.*) @cancjs/coroutine/gen (cancGen.*)
async function canc.async cancGen.async
await canc.await cancGen.await
throw canc.throw cancGen.throw
for await canc.forAwait cancGen.forAwait

Declared failures

Coroutines track typed failures from awaited promises and explicit error steps. The failure set is carried on the returned CancelablePromise<TReturn, TFailure> or ICancAsyncGenerator<TEmit, TReturn, TNext, TFailure>.

Three annotation forms

  1. Inferred from body: canc.async automatically infers the union of all awaited promise failures and explicit canc.throw steps:
const loadUser = canc.async(function* (id: string) {
  const user = yield* canc.await(fetchUser(id)); // CancelablePromise<User, UserNotFoundError>
  if (!user.active) {
    return yield* canc.throw(new InactiveUserError(id));
  }
  return user;
}); // Returns CancelablePromise<User, UserNotFoundError | InactiveUserError>
  1. Generator body annotation with AsyncResult: When declaring a generator function separately from canc.async, annotate its return type as AsyncResult<TResult, TFailure>:
function* userCoroutine(id: string): AsyncResult<User, UserNotFoundError | InactiveUserError> {
  const user = yield* canc.await(fetchUser(id));
  if (!user.active) {
    return yield* canc.throw(new InactiveUserError(id));
  }
  return user;
}

const loadUser = canc.async(userCoroutine);
  1. Producer body annotation with AsyncGenResult: For async generators wrapped with cancGen.async, use AsyncGenResult<TEmit, TReturn, TFailure>:
function* streamEvents(): AsyncGenResult<EventItem, void, NetworkError> {
  const event = yield* cancGen.await(fetchNextEvent());
  yield event;
}

const events = cancGen.async(streamEvents);

Parameter order in AsyncGenResult

AsyncGenResult<TEmit, TReturn = void, TFailure = unknown> takes three parameters in order of relevance to async generators:

  • TEmit: the type of items yielded to consumers (emitted stream items).
  • TReturn: the return type when the generator completes.
  • TFailure: the declared failure type union.

This ordering allows specifying a return type without requiring a failure type. It differs from AsyncResult<TResult, TFailure = unknown>, where TResult comes first because standard coroutines return a single result.

Strict AsyncResult type matrix and bare yield

When a generator is annotated with a specific failure set like AsyncResult<number, FooError>, TypeScript enforces that all yielded steps match the declared failures:

  • Primitives: Bare yield 42 or yield 'hello' is permitted because primitives cannot carry failure phantoms.
  • Awaited steps: yield* canc.await(promise) verifies that any failure declared on promise is assignable to the declared TFailure.
  • Explicit error steps: yield* canc.throw(err) verifies that err is assignable to TFailure.
  • Promises: Bare-yielding a promise directly is rejected with compiler error TS2322 because promises do not carry failure brand phantoms. Use yield* canc.await(promise).
  • Plain objects: Yielding a plain object directly (without canc.await or canc.throw) causes a TypeScript compilation error (TS2353 for object literals or TS2559 for object variables) because plain objects do not carry failure brand phantoms.

Annotation requirements for bare yield and compiler errors

When using bare yield expressions rather than yield*, TypeScript enforces two rules:

  1. Unannotated bodies cannot bare-yield without a return-type annotation: Under strict compiler settings (strict: true or noImplicitAny: true), an unannotated generator function cannot bare-yield a value. TypeScript reports:
error TS7057: 'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation.

To resolve this error, annotate the generator function return type with AsyncResult<TResult, TFailure> (or AsyncResult<TResult> when no failure set is declared):

// Fails with TS7057: unannotated generator lacks a return-type annotation
const unannotated = canc.async(function* () {
  const value = yield 42;
  return value;
});
// Fixed: annotate generator return type with AsyncResult
const annotated = canc.async(function* (): AsyncResult<number> {
  const value = yield 42;
  return (value as number) + 1;
});
  1. Bodies annotated with a concrete failure set cannot bare-yield a promise: When a generator body is annotated with a concrete failure set (such as AsyncResult<User, UserNotFoundError>), bare-yielding a promise is rejected by the compiler:
error TS2322: Type 'Promise<User>' is not assignable to type 'TPrimitiveYield | Failing<UserNotFoundError>'.
  Type 'Promise<User>' has no properties in common with type 'Failing<UserNotFoundError>'.

A native promise carries no failure brand properties, so TypeScript's weak-type check rejects it. Bare-yielding an object literal similarly causes error TS2353: Object literal may only specify known properties, and yielding an object variable causes error TS2559: Type '{ ... }' has no properties in common with type 'Failing<UserNotFoundError>'.

To resolve this error, await promises using yield* canc.await(...):

// Fails with TS2322: bare yield of promise into concrete failure set
const loadUser = canc.async(function* (): AsyncResult<User, UserNotFoundError> {
  const user = yield fetchUser(id);
  return user as User;
});
// Fixed: await using canc.await
const loadUserFixed = canc.async(function* (): AsyncResult<User, UserNotFoundError> {
  const user = yield* canc.await(fetchUser(id));
  return user;
});

Non-tail yield* canc.throw(...) and TS2355

yield* is a language expression rather than a function call. TypeScript does not automatically recognize that code following yield* canc.throw(...) is unreachable.

Writing a bare yield* canc.throw(err) in a non-tail position inside a function with a declared non-void return type results in compiler error TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.

To resolve this, prefix the statement with return:

return yield* canc.throw(new FooError());

Because canc.throw returns Generator<..., never, ...>, its never return type widens to any return type required by the function.

Error handling inside coroutines

Errors raised by canc.throw or rejected promises can be caught inside the generator using standard try/catch blocks and inspected with a guard made by createIsError from @cancjs/promise:

import { createIsError } from '@cancjs/promise';

const isNotFound = createIsError(UserNotFoundError);

const safeLoad = canc.async(function* (id: string) {
  try {
    return yield* canc.await(fetchUser(id));
  } catch (err) {
    if (isNotFound(err)) {
      return null;
    }
    throw err;
  }
});

If an error is uncaught inside the coroutine, the returned promise rejects with that error. Callers can handle rejections using @cancjs/promise error utilities or global rejection handlers.

Failures of awaited library calls

A step contributes only the failures its promise declares. Library calls that cannot promise their list is complete write an open set, X | Unlisted. Inside a coroutine the step contributes X and the Unlisted marker is dropped, so the result of the coroutine lists declared failures only. That makes it a closed set, and the reason in a catch on the result narrows to it, unlike the any reason of a raw promise with an open set.

What each step contributes:

  • CancelablePromise<T, Foo>: Foo
  • CancelablePromise<T, Foo | Unlisted>: Foo
  • CancelablePromise<T, never> and CancelablePromise.resolve(1): nothing
  • a one-argument CancelablePromise<T>: unknown, so the result is undeclared and its catch reason is any
  • a native promise, a foreign thenable, a plain value or any: nothing
  • canc.throw(e): the type of e. A plain throw in the body is not tracked
  • canc.await.race and canc.await.all: the union of their members. canc.await.any contributes AggregateError, and canc.await.allSettled nothing
const loadUser = canc.async(function* (id: string) {
  const res = yield* canc.await(cancelableFetch(`/users/${id}`)); // TimeoutError | Unlisted, contributes TimeoutError
  const body = yield* canc.await(res.json() as Promise<{ id: string }>); // native, contributes nothing
  const row = yield* canc.await(timeout(db.query(body.id), 500)); // TimeoutError | Unlisted, contributes TimeoutError
  if (!row) {
    return yield* canc.throw(new NotFoundError(body.id));
  }
  return row.name;
});
// (id: string) => CancelablePromise<string, TimeoutError | NotFoundError>

The set lists declared failures only, and the promise can still reject with something unlisted at runtime, such as a network TypeError from fetch or a SyntaxError from json(). After the guards exhaust the set, the reason in the last branch is never. End the handler with a fallback that does not read the value, such as a rethrow, or use catchErrors:

const isNotFound = createIsError(NotFoundError);

loadUser('1').catch((e) => {
  if (isTimeoutError(e)) return 'slow';
  if (isNotFound(e)) return 'missing';
  throw e; // e is never here, the runtime may still reject with a TypeError or SyntaxError
});

Reading a property of the reason in that last branch is a compile error, for example Property 'message' does not exist on type 'never'.

Narrowing the reason can break code that compiled against 1.0, where a coroutine result always had a catch reason of any. Each of these steps now declares a failure, so e.code or e.response on the reason stops compiling:

  • canc.await.any([...]) or canc.await(CancelablePromise.any([...])): the reason is AggregateError
  • canc.await(timeout(promise, ms)), over a native, declared or one-argument input: the reason is TimeoutError
  • canc.await(cancelableFetch(url)): the reason is TimeoutError
  • a step on any promise that declares a type, such as CancelablePromise<T, Foo>: the reason is that set

Native steps, one-argument steps, canc.await.race and canc.await.all with native members, and a try/catch around a step are unaffected.

To keep the old loose reason for a coroutine, annotate the outer function with a one-argument promise. A declared result fits a one-argument slot, and the annotation wins:

const loadAny: () => CancelablePromise<number> = canc.async(function* () {
  return yield* canc.await(timeout(nativeP, 10));
});

loadAny().catch((e) => e.response); // e is any

Annotating the body as AsyncResult<number> with no failure type gives the same result, and so does typing the handler parameter at one call site, as in .catch((e: any) => e.code). To use the narrowed reason instead, handle it with guards and a rethrowing fallback as above.

Write yield* canc.await(promise) rather than a bare yield promise. A bare yield of a promise cannot carry its failure, and TypeScript can merge it with a native step of the same value type and lose the declared failure.

Awaiting several things at once

canc.await.all, .race, .any, .allSettled and .try fold a combinator into a single step. Cancellation semantics come from @cancjs/promise: race and any give up the losers, all gives up the rest on the first rejection. An input that something else still consumes keeps running; only an input with no consumer left is canceled.

const [profile, orders] = yield * canc.await.all([
  fetchProfile(id),
  fetchOrders(id)
]);

Consuming an async iterable

canc.forAwait walks a source and runs a callback per item. Every pull is a cancellation point, and canceling the coroutine closes the source:

const collectTokens = canc.async(function* (prompt: string) {
  let answer = '';

  yield* canc.forAwait(streamCompletion(prompt), (token) => {
    answer += token;

    if (answer.length > 4000) {
      return false; // stops the loop, the source is closed
    }
  });

  return answer;
});

The callback can be a plain function, a generator function, or a coroutine. Use a generator function when the per-item work itself has to be cancelable:

yield* canc.forAwait(chunkStream, function* (chunk) {
  yield* canc.await(saveChunk(chunk));
});

canc.forAwait.toArray(source) collects a finite source into an array instead.

The loop handle form

Called without a callback, canc.forAwait returns an iterable handle instead of driving a callback. A for...of loop over yield* canc.forAwait(source) keeps the body in the coroutine's own frame, so break, continue and return are native keywords, and the body closes over surrounding bindings directly:

const saveUntilFull = canc.async(function* (chunkStream: AsyncIterable<Chunk>, isFull: () => boolean) {
  for (const chunk of yield* canc.forAwait(chunkStream)) {
    yield* canc.forAwait.next(); // pulls the next item, advance at the top of the body

    if (chunk.skip) continue;
    if (isFull()) break;

    yield* canc.await(saveChunk(chunk));
  }
});

Both spellings

  • yield* canc.forAwait.next(): argument-free sugar for the common single-loop case. It resolves the innermost open loop handle without requiring a temporary variable binding.
  • yield* loop.next(): explicit advance on a stored handle (const loop = yield* canc.forAwait(src)). Use this when two loops are open at once and the advance must name one of them, or for yield* loop.return(), which requires a handle binding.
const outerLoop = yield* canc.forAwait(streamA);

for (const a of outerLoop) {
  yield* outerLoop.next();

  const innerLoop = yield* canc.forAwait(makeStreamB());
  for (const b of innerLoop) {
    yield* canc.forAwait.next();
    handlePair(a, b);
  }
}

The sugar resolves handle-form loops only, so inside a callback-form canc.forAwait body it advances the enclosing handle loop; use the stored-handle form when managing loops across both styles. The sugar also yields unknown, so a body annotated with a concrete failure set uses the stored handle instead.

The advance rule and lookahead

Creating the handle with yield* canc.forAwait(source) prefetches the first item before the loop body runs, even if the body never executes. Each advance (yield* canc.forAwait.next() or yield* loop.next()) pulls the next item. At any moment, the source is at most one item ahead of the body.

Follow these rules for advancing the loop:

  1. Default: advance first. Place yield* canc.forAwait.next() (or yield* loop.next()) at the top of the loop body. Because the advance runs before any branching logic, continue works directly without ceremony. On an early break, the lookahead item already pulled is discarded. For ordinary sources (arrays, paginated HTTP queries, database cursors), this costs at most one extra request.

  2. Exception: destructive sources. For one-shot, destructive sources where a discarded lookahead item means a lost message (such as a queue, a message channel, or a single-use stream), advance last and do not use continue, or use the callback form of canc.forAwait.

The advance-first default avoids hidden runtime bugs. An advance-last loop that contains a continue branch without advancing will throw IterationError on the following turn. Because error and skip branches are often rarely exercised in tests, advance-first is the safer default.

Advancing the same handle twice in one turn throws IterationError. The rule applies to loop.next() and canc.forAwait.next() when both target the same handle. After an inner loop is exhausted, canc.forAwait.next() targets the innermost open loop, which may be the outer loop. Use the explicit handle in nested loops when the target matters.

A handle iterates once; calling [Symbol.iterator]() a second time on the same handle throws IterationError.

Cleanup timing

Exhaustion and an explicit yield* loop.return() finish the source's cleanup at that point. A plain break goes through the synchronous iterator protocol instead, which cannot await in place, so cleanup there finishes before the coroutine settles rather than before the line after break. Call yield* loop.return() right after a break when that ordering matters. yield* loop.return() requires the stored-handle spelling and the sugar has no .return equivalent, so a body that needs cleanup to finish at the break statement stores the handle.

Reach for the handle form when the loop body needs a native break, continue, or return out of the coroutine. Use the callback form above for plain streaming with no early exit.

Producing an async iterable

cancGen.async turns a generator function into a cancelable async generator. Inside it, yield emits and yield* cancGen.await(...) awaits:

import * as cancGen from '@cancjs/coroutine/gen';

const exportVideo = cancGen.async(function* (chunkIds: string[]) {
  for (let index = 0; index < chunkIds.length; index++) {
    yield* cancGen.await(transcodeChunk(chunkIds[index])); // internal step
    yield Math.round(((index + 1) / chunkIds.length) * 100); // progress, emitted
  }
});

for await (const progress of exportVideo(chunkIds)) {
  updateProgressBar(progress);
}

cancGen.forAwait consumes another source from inside a producer without emitting its items, and cancGen.delegate(source) re-emits them. Delegation needs its own helper because a synchronous generator cannot yield* an async iterable. Like yield*, it passes the values sent with next() and the errors sent with throw() on to the source, and the source's return value becomes the result of the delegation.

Canceling a pending step (iterator.next().cancel()) or aborting the signal passed in the options cancels the producer the same way canc.async cancels a coroutine. Its finally blocks run to the end with shielded steps, the canceled step stays pending until they finish, and an error thrown by that cleanup rejects the step. The signal is watched from the producer's first pull until it ends, so an abort between two pulls cleans it up too. Cleanup started by a consumer return() or break is shielded as well. If the producer's signal aborts during that cleanup, the active return completes with its normal result or rejects with the cleanup error. Explicitly canceling the return step still cancels it after cleanup.

Class methods

canc.async wraps a generator function into a plain function, so placing it on a class is the caller's decision. There are several ways to do it, depending on whether you use decorators and whether you need TypeScript-correct types at the call site.

With decorators

The decorators package does it declaratively. The getter style is the recommended form in TypeScript:

import * as canc from '@cancjs/coroutine';
import { AsyncMethod } from '@cancjs/decorators';

class InvoiceService {
  @AsyncMethod()
  get load() {
    return canc.async(function* (this: InvoiceService, invoiceId: string) {
      return yield* canc.await(fetchInvoice(invoiceId));
    }, this);
  }

  @AsyncMethod({ bind: true }) // per instance, safe to detach as a callback
  get loadBound() {
    return canc.async(function* (this: InvoiceService, invoiceId: string) {
      return yield* canc.await(fetchInvoice(invoiceId));
    }, this);
  }
}

A getter's return type is inferred from its body, so canc.async(...) flows through correctly and the call site sees CancelablePromise<T>.

In plain JavaScript the shorter method style works too, because there is no static type to be wrong:

class IssueClient {
  @AsyncMethod()
  *loadIssue(issueId) {
    return yield* canc.await(this.api.issue(issueId));
  }
}

In TypeScript, a method decorator cannot change the declared return type of the method it decorates, so a decorated *load() generator keeps its generator type at the call site and every caller needs a cast. Use the getter style instead.

With asyncMethod / bindMethod

Two helpers do the same work without decorators. Call them in the constructor. asyncMethod is the runtime counterpart of @AsyncMethod({ bind: true }) and bindMethod of @BindMethod(), so the member's kind decides what happens to it, exactly as it does under the decorators.

On a getter, both read it once, bind the result to the instance, and install it as an own property, so the getter is never called again. Neither wraps here: the getter already returned the finished function.

import * as canc from '@cancjs/coroutine';

class InvoiceService {
  constructor() {
    // per instance, equivalent to @AsyncMethod({ bind: true })
    canc.asyncMethod(this, 'load');
  }

  get load() {
    return canc.async(function* (this: InvoiceService, invoiceId: string) {
      return yield* canc.await(fetchInvoice(invoiceId));
    }, this);
  }
}

On a generator method, or a class field holding a generator function, the member is still raw, so asyncMethod wraps it with canc.async bound to the instance while bindMethod only binds it. This is the shorter form, and it has the same TypeScript problem as the decorated method style above, so keep it for JavaScript:

class InvoiceService {
  constructor() {
    canc.asyncMethod(this, 'load');
  }

  *load(invoiceId) {
    return yield* canc.await(fetchInvoice(invoiceId));
  }
}

asyncMethod takes coroutine options as a third argument, which the decorators do not: canc.asyncMethod(this, 'load', { shield: true }).

Prototype assignment (JS only)

In plain JavaScript, a generator method can be replaced on the prototype directly:

class InvoiceService {
  *load(invoiceId) {
    return yield* canc.await(fetchInvoice(invoiceId));
  }
}

InvoiceService.prototype.load = canc.async(InvoiceService.prototype.load);

This is the cheapest form: one wrapped function per class, shared by all instances. In TypeScript, the call site still sees the generator's return type. Interface merging works when the class does not declare the member itself, but the type must be hand-written rather than inferred. Use a getter style instead.

Prototype assignment with declaration merging

TypeScript users can correct the type by declaring an interface with the same name as the class, then assigning to the prototype:

interface InvoiceService {
  load(invoiceId: string): CancelablePromise<Invoice>;
}

class InvoiceService {}

InvoiceService.prototype.load = canc.async(function* load(this: InvoiceService, invoiceId: string) {
  return yield* canc.await(fetchInvoice(invoiceId));
});

The call site now sees CancelablePromise<T>, and the wrapped function is shared by all instances, the same as the plain JavaScript form. The type is hand-written rather than inferred, so it can drift from the implementation without the compiler noticing. The this annotation must be added by hand. The member appears uninitialized in the class body, which can be confusing to readers.

The getter style remains the recommendation, as it infers the return type and keeps the initialization visible inside the class.

Class field

A class field avoids the prototype entirely, at the cost of one wrapped function per instance:

class InvoiceService {
  load = canc.async(function* (this: InvoiceService, invoiceId: string) {
    return yield* canc.await(fetchInvoice(invoiceId));
  }, this);
}

This is the simplest form for one-off classes, but the method does not participate in super lookup and cannot be overridden from a subclass through the prototype chain.

Things that do not work

  • passing an async function or an async function* to canc.async. There is nothing to drive. The returned promise rejects with a TypeError saying so. Pass a plain generator function, and turn each await into yield* canc.await(...), which is the point: an await inside an async body escapes the cancel chain.
  • wrapping a coroutine again. canc.async throws a TypeError on the spot rather than trying to drive the CancelablePromise it would get back as if it were a generator.
  • yield canc.await(x) without the star. The step resumes with a generator object instead of the value, and cancellation is never wired.
  • annotating a body as Generator<unknown, T, any>, or as any. Both collapse step types. Let inference do its work, or use AsyncResult<T> where a generator has no enclosing wrapper to carry its type.
  • awaiting a plain, non-cancelable promise and expecting the work to stop. The chain stops, the operation does not. Make it cancelable at its source with cancelify or promisify from the toolbox.

API

@cancjs/coroutine

Export Alias Description
cancAsync(genFn, ctx?, options?) canc.async Wraps a generator function into a function returning a CancelablePromise
cancAwait(value) canc.await One step, used as yield* cancAwait(value)
cancAwait.all / .race / .any / .allSettled / .try Combinators folded into a single step, tuple types preserved
cancThrow(error) canc.throw Yieldable throw step for declaring and raising errors inside coroutines
cancForAwait(source, callback) canc.forAwait Consumes an async or sync iterable, one cancellation point per item
cancForAwait(source) canc.forAwait Called without a callback, returns a loop handle for a native for...of body
cancForAwait.next() canc.forAwait.next Advances the innermost open loop handle, pulling the next item
cancForAwait.toArray(source) Collects a source into an array
asyncMethod(instance, key, options?) Installs the member as an own property, wrapping a method or field with cancAsync
bindMethod(instance, key) Installs the member as an own property, bound to the instance, never wrapped
BreakError, isBreakError Breaking out of a stream from deeper code
IterationError Thrown by a loop handle used out of turn: skipped next(), or iterated a second time
AsyncResult<TResult, TFailure> Return type for a generator body with optional failure set
ICancForAwaitLoop<T> Type of the handle returned by the callback-less form of cancForAwait

options are CancelablePromise options and configure the promise the coroutine returns. ctx sets this for the generator body; null and undefined leave the call's own this.

@cancjs/coroutine/gen

Export Alias Description
cancGenAsync(genFn, options?) cancGen.async Wraps a generator function into a function returning a cancelable async generator
cancGenAwait(value) cancGen.await Internal step inside a producer, not emitted
cancGenAwait.all / .race / .any / .allSettled / .try Same combinators for producer bodies
cancGenThrow(error) cancGen.throw Yieldable throw step inside a producer body
cancGenForAwait(source, callback) cancGen.forAwait Consumes a source inside a producer without emitting its items
cancGenForAwait.toArray(source) Collects a source into an array
cancGenDelegate(source) cancGen.delegate Re-emits another async iterable to the consumer
AsyncGenResult<TEmit, TReturn, TFailure> Return type for a producer body (emit type, return type, failure set)

Compatibility

Node.js 18 and later, current browsers, TypeScript 4.2 and later. Generators are required, so an ES5 build target needs downlevelIteration. Everything else follows @cancjs/promise.

Documentation

  • yield vs yield* for the typing limitation behind the starred form, and how redux-saga and MobX flow hit the same wall
  • @cancjs/promise for the cancellation model itself
  • Decorators for class methods
  • Toolbox for making existing APIs cancelable
  • Examples: demo-coroutine for the basics, app-ai-rag-pipeline and app-ws-progress for streaming producers and consumers

Contributing

You are welcome to participate through issues and pull requests!

License

MIT