- TypeScript 100%
@okikio/future #
Future wraps a generator so a caller can consume its values, wait for its result, and request changes to its execution. Use it when an operation has meaningful steps or progress values that a single Promise does not expose.
Control is cooperative. A Future can pause between generator steps and pass a cancellation signal to the operation. It cannot pause arbitrary JavaScript or cancel an existing Promise's producer. In particular, from(fetch(url)) receives a request that has already started; the wrapper cannot add an abort signal to that request afterward.
Start with an operation #
These examples use source imports from a checkout. The manifest currently identifies the package as version 0.0.0.
import { from } from "./from.ts";
const work = from(async function* () {
yield "first step";
yield "second step";
return "done";
});
const result = await work.toPromise();
console.log(result); // "done"
Calling from() creates the Future. Consuming it with next(), an async iterator, toPromise(), or await advances the generator. toPromise() consumes intermediate values and returns the generator's final result.
If the caller needs the intermediate values, use one iterator:
import { from } from "./from.ts";
const work = from(async function* () {
yield "reading";
yield "checking";
return { accepted: true };
});
const iterator = work[Symbol.asyncIterator]();
let step = await iterator.next();
while (!step.done) {
console.log(step.value); // "reading", then "checking"
step = await iterator.next();
}
console.log(step.value); // { accepted: true }
A yield value is an intermediate value chosen by the operation. A return value is the final result. Do not rely on several consumers to receive the same values: a Future exposes its generator, not a broadcast progress feed.
Choose an input with the right lifetime #
Input to from() |
What the wrapper receives | Consequence |
|---|---|---|
| A generator function | A factory for the operation | The operation starts when consumed and can receive the Future's cancellation controller and disposal stack. |
| A function returning a value or Promise | A factory that runs when consumed | Pass its cancellation signal to any I/O that supports it. |
| An existing Promise | Work that may already be running | The Future does not acquire control over the Promise's producer. |
| An existing iterator or stream | An object with its own consumption state | Wrapping or resetting the Future does not create a fresh input. |
| A value or built-in iterable | The supplied value or sequence | The wrapper yields its values; it does not invent progress or cancellation for external work. |
For repeatable work, provide a factory that creates fresh resources each time. Resetting a wrapper around an existing Promise does not send a second request or undo the first request's effects.
Pause between steps #
pause() changes the Future's state. The iteration loop checks that state between steps and waits until resume() changes it again.
A pause does not interrupt a request, timer, CPU loop, or other operation that is already running inside the current step. Keep steps small enough for the responsiveness the application needs. If an external API supports its own pause mechanism, connect that mechanism explicitly.
Connect cancellation to the actual operation #
A function passed to from() receives an AbortController. Pass its signal to the I/O that must stop:
import { from } from "./from.ts";
const work = from(async function* (abort) {
abort.signal.throwIfAborted();
yield "requesting";
const response = await fetch("https://example.com/data.json", {
signal: abort.signal,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json();
});
// Start consumption. Application code can request cancellation while it runs.
const result = work.toPromise();
An application can call work.cancel(reason) to abort that controller. Handle the result's rejection in the caller. The producer must observe the signal for cancellation to stop its I/O.
The iteration error path attempts to return from the generator so its finally block can run. Cancellation notification, generator termination, and disposal are separate events. Do not treat a cancellation event as proof that every resource has been released.
Give resources an owner #
The operation also receives an AsyncDisposableStack. Register resources there when the Future owns their cleanup. dispose() first waits for cancel(). Only after that wait succeeds does it dispose registered resources, remove listeners, and clear operation references. Symbol.asyncDispose calls the same method.
Keep borrowed resources outside that stack unless the caller explicitly transfers ownership. Normal result delivery is not a substitute for an explicit cleanup policy. See disposal.ts for the registration and disposal helpers.
Current lifecycle limits #
Source inspection shows unresolved paths in this branch. These are implementation defects, not limits that cooperative cancellation alone explains:
- A rejected cancellation can skip disposal.
cancel()waits for a cancellation event with a one-second timeout that rejects. Its abort listener is attached only when consumption starts, and an already-aborted controller does not emit another abort event. Cancellation before consumption or after an earlier abort therefore needs explicit handling.dispose()awaitscancel()without a cleanupfinallyblock; if that call rejects, stack disposal and listener removal do not run. - Cancellation during a pause needs explicit termination handling. The pause loop exits for running or idle events, but has no cancellation branch. A cancellation notification alone therefore does not establish that the paused iterator ended.
These paths have not been reproduced by this documentation review. Fix and test them before relying on cancellation or disposal to finish. The examples above explain the intended consumption and signal connections; they do not establish a usable release.
Find the relevant operation #
| Need | Source |
|---|---|
| Consume, pause, resume, cancel, reset, clone, or dispose a Future | future.ts |
| Convert a value, Promise, iterable, iterator, stream, or function | from.ts |
Compose concurrent work with all, allSettled, race, some, or withConcurrencyLimit |
concurrency.ts |
Compose sequential work with scope |
scope.ts |
| Start work in the background | background.ts |
| Set a deadline or delay | deadline.ts |
| Associate an external cancellation source | abortable.ts |
| Create external result resolvers | resolvers.ts |
| Split values by a rule | split.ts |
| Inspect status names and event types | status.ts and events.ts |
The concurrency and scope functions consume the Futures they receive. They cannot delay work that a caller already started while constructing those inputs. Pass operation factories when start order matters.
Follow the implementation #
from.ts selects a conversion based on the input. The conversion creates a Future, whose private iteration loop in future.ts advances the operation and observes pause or cancellation state. The operation supplies yielded values and a final result. disposal.ts registers resources with the stack that dispose() releases.
When changing this flow, check both the ordinary result and early termination. Preserve the distinction between the operation's result, status events, cancellation requests, and resource cleanup. A change that only updates a status label does not prove that the producer stopped.
Validate a change #
Tests are colocated as *_test.ts. Read the test for the operation being changed and run it before expanding to the full suite. The repository declares deno task test in deno.jsonc.
The current branch still needs its test import aliases and package export paths reconciled before that command and every advertised subpath can be treated as a working consumer path. Some export targets named in deno.jsonc do not exist in this checkout, and the added tests use @std/testing/bdd and @std/expect without matching import aliases. A test file's presence is not a passing result.
For lifecycle changes, include cancellation during a pending step, generator cleanup, resource disposal, and reuse of stateful inputs. Verify the actual consumer flow before making runtime or release claims.
License #
See LICENSE for the MIT license.