race
race resolves or rejects with whichever JoinHandle<T> in an array settles first.
Signature
race<T>(handles: JoinHandle<T>[]): Promise<T>Once one handle settles, race cooperatively cancels every other handle through the same mechanism cancel/JoinHandle<T>.abort() use, a handle that has already settled by then (the winner itself, or a loser that happened to finish between the race settling and this cleanup running) is left alone, since cancelling an already-settled Promise is a harmless no-op. Every handle passed to race is consumed the same way .join() consumes one, so reusing a handle already passed to race, or to joinAll, or to its own .join(), is rejected at compile time (E3033).
tyrus
import { spawn, race, sleepAsync } from "tyrus:task";
async function fetchReplica(id: i32, delayMs: u64): Promise<i32> {
await sleepAsync(delayMs);
return id;
}
async function main(): Promise<void> {
// Two redundant replicas answer the same request; `race` returns
// whichever answers first and cancels the other one, no need to wait
// for a reply nothing will use.
const replicaA = spawn(async (): Promise<i32> => await fetchReplica(1, 50));
const replicaB = spawn(async (): Promise<i32> => await fetchReplica(2, 5));
const winner: i32 = await race([replicaA, replicaB]);
print(winner);
}