Skip to content

spawn ​

spawn runs an async task concurrently with its caller and returns a JoinHandle<T> for it.

Signaturespawn<T>(task: () => Promise<T>): JoinHandle<T>

JoinHandle<T>.join(): Promise<T> resolves to the task's result, and JoinHandle<T>.abort(): void cooperatively cancels it through the same mechanism as cancel. .join() consumes the handle, so joining the same handle twice, or calling .abort() after .join(), is rejected at compile time (E3033); .abort() itself does not consume the handle, so it may be called any number of times before .join(). A thrown error inside a spawned task rejects the Promise<T> join() returns, exactly like any other async function. Like Promise<T>, JoinHandle<T> is a native type and never needs to be imported.

await spawn(...) directly, and await spawn(...).join() chained in the same expression, are both rejected at compile time (E3031): both throw away the only way to hold onto the task and do other work while it runs in the background. A discarded JoinHandle<T>, spawn(...); as a bare statement, never storing the result, is rejected the same way an unused Promise<T> is, since its result or rejection could never be observed.

Each call to tyrus:net's resolve below is a real network round trip that can take a while. Spawning both lookups lets the second one start before the first has replied, instead of waiting its turn, see the Playground page under Tooling for why this example does not run there:

tyrus
import { NetError, resolve } from "tyrus:net";
import { spawn } from "tyrus:task";

async function lookup(host: string): Promise<string[]> {
    try {
        const addresses: string[] = await resolve(host, 2_000);
        return addresses;
    } catch (error: NetError) {
        return [];
    }
}

async function main(): Promise<void> {
    // Two independent, real network round trips, each one could take
    // hundreds of milliseconds. Spawning both means the second lookup starts
    // before the first one has replied, instead of waiting its turn.
    const first = spawn(async (): Promise<string[]> => {
        const addresses: string[] = await lookup("example.com");
        return addresses;
    });
    const second = spawn(async (): Promise<string[]> => {
        const addresses: string[] = await lookup("localhost");
        return addresses;
    });

    const exampleAddresses: string[] = await first.join();
    const localAddresses: string[] = await second.join();

    print(exampleAddresses.length > 0);
    print(localAddresses.length > 0);
}