Class FiberController<T>
Source: FiberController.ts
Controls the lifecycle of an async "fiber" — a long-running async task that can pause itself (ctx.sleep()), be resumed externally (controller.resume()), and be aborted at any time (controller.abort()).
Useful for implementing idle-wait loops, worker-pool members, or any pattern where an async function needs to wait for an external signal to continue.
Import
import { FiberController } from '@litert/utils-async';Constructor
new FiberController<T = null>(options: IFiberOptions<T>)Starts the fiber execution immediately on construction. The fiber runs options.main(ctx) and exits when that function returns or throws.
Parameters
- Parameter
options: IFiberOptions<T>— SeeIFiberOptions.
Properties
| Name | Type | Description |
|---|---|---|
data: T | T | The shared data object passed to the fiber. |
Methods
isSleeping
isSleeping(): boolean;Returns true if the fiber is currently paused in ctx.sleep().
isRunning
isRunning(): boolean;Returns true if the fiber execution is currently active (not sleeping and not exited).
isExited
isExited(): boolean;Returns true if the fiber has finished execution (returned or thrown).
resume
resume(): boolean;Resumes a sleeping fiber. Returns true if the fiber was sleeping and was successfully resumed; false otherwise.
abort
abort(): void;Aborts the fiber by triggering its internal AbortSignal. If the fiber is sleeping, it will wake up and receive the abort signal. The fiber execution is responsible for observing the signal and exiting gracefully.
waitForExit
waitForExit(): Promise<void>;Returns a Promise that resolves when the fiber exits.
waitForSleep
waitForSleep(): Promise<void>;Returns a Promise that resolves the next time the fiber calls ctx.sleep().
Examples
import { FiberController } from '@litert/utils-async';
interface IWorkerData {
queue: string[];
}
const fiber = new FiberController<IWorkerData>({
data: { queue: [] },
main: async (ctx) => {
while (true) {
while (ctx.data.queue.length > 0) {
const item = ctx.data.queue.shift()!;
console.log('Processing:', item);
}
// Wait for more work
try {
await ctx.sleep();
} catch {
// Aborted
break;
}
}
},
});
// Submit work and resume the fiber
fiber.data.queue.push('task-1');
fiber.resume();
// Eventually shut down
fiber.abort();
await fiber.waitForExit();