Offload functions to worker threads with shared memory primitives for Node.js.
1import { runStreamOnDedicated } from './dedicated-runner.ts';
2import type { WorkerHandle } from './runner.ts';
3
4let nextUid = 0;
5
6/**
7 * A deferred streaming computation. When dispatched via a {@link Runner} or iterated directly,
8 * returns an `AsyncIterable` of yielded values instead of a `Promise`.
9 * Created by calling an `async function*` wrapped with {@link mo}.
10 */
11export class AsyncIterableTask<T> implements AsyncIterable<T> {
12 readonly uid: number;
13 readonly id: string;
14 readonly args: unknown[];
15 worker?: WorkerHandle;
16
17 /** @param id - The moroutine identifier (module URL + index).
18 * @param args - The arguments to pass to the worker generator function. */
19 constructor(id: string, args: unknown[]) {
20 this.uid = nextUid++;
21 this.id = id;
22 this.args = args;
23 }
24
25 /** Enables `for await...of` by dispatching to a dedicated worker. @returns An iterator of yielded values. */
26 [Symbol.asyncIterator](): AsyncIterator<T> {
27 const iterable = runStreamOnDedicated<T>(this.id, this.args);
28 return iterable[Symbol.asyncIterator]();
29 }
30}