Async and Await
tyrus supports executable async functions, await expressions, native Promise<T> values, and structured rejection handling.
Async Functions
Declare an async function with the async keyword. It returns a Promise<T> that resolves to the inner type.
async function fetchUser(): Promise<string> {
return "Ada";
}
async function main(): Promise<void> {
const name: string = await fetchUser();
print(name); // "Ada"
}A void async function returns Promise<void> and does not carry a payload.
async function logMessage(message: string): Promise<void> {
print(message); // "hello from tyrus"
}
async function main(): Promise<void> {
await logMessage("hello from tyrus");
}Top-Level Await
A parameterless async function main(): Promise<void> can suspend at multiple top-level await statements.
async function fetchConfig(): Promise<string> {
return "config-data";
}
async function main(): Promise<void> {
print("loading config...");
const config: string = await fetchConfig();
print(config); // "config-data"
print("loading user...");
const user: string = await fetchUser();
print(user); // "Ada"
}Arrow Async Functions
Async arrow functions follow the same syntax.
const fetchData = async (): Promise<i32> => {
return 42;
};
async function main(): Promise<void> {
const value: i32 = await fetchData();
print(value); // 42
}Mutable Objects Across Await
A mutable object whose required stored fields are all Copy values can remain live across suspensions. Its Copy fields may be changed in place, and the whole binding may be replaced with another compatible object literal.
interface Cursor {
row: i32;
column: i32;
visible: boolean;
}
async function move(): Promise<void> {
let cursor: Cursor = { row: 1, column: 2, visible: true };
await Promise.resolve();
cursor.row = 3;
cursor = { row: 4, column: 5, visible: false };
await Promise.resolve();
print(cursor.column);
}Mutable objects with supported heap-owned fields may be replaced as a whole or updated field by field. Assignment to string, array, optional, and nested object fields evaluates and deeply clones the replacement before releasing the previous field, so self-derived assignments remain valid. Mutating string-array field methods such as push, splice, fill, and sort operate directly on the frame-owned field. Every recursively owned local carries an initialization bit, and generated type-specific drop glue releases only initialized values exactly once during replacement or frame destruction.
interface Snapshot {
count: i32;
label: string;
tags: string[];
note?: string;
}
async function refresh(): Promise<void> {
let snapshot: Snapshot = { count: 1, label: "first", tags: ["static"] };
await Promise.resolve();
snapshot.count = 2;
snapshot.label = snapshot.label.toUpperCase();
snapshot.tags = "direct,field".split(",");
snapshot.tags.push("tail");
snapshot.note = snapshot.label;
await Promise.resolve();
snapshot = {
count: 3,
label: "second".toUpperCase(),
tags: "owned,array".split(","),
note: "present".toUpperCase(),
};
await Promise.resolve();
print(snapshot.label);
}Nested Control Flow
Suspensions may appear through arbitrarily nested blocks, conditional branches, loops, switches, and structured error handling. The async state machine preserves active loop instances and lexical scopes between sibling suspension paths, so break, continue, branch-local bindings, and statements before or after each suspension retain their normal behavior. Both branches of a nested if may contain independent suspension chains with different lengths, payload types, and bindings; the condition is evaluated once.
async function process(enabled: boolean): Promise<i32> {
let total: i32 = 0;
let outer: i32 = 0;
while (outer < 2) {
outer += 1;
let inner: i32 = 0;
while (inner < 3) {
inner += 1;
if (inner === 2) {
await Promise.resolve();
continue;
}
if (outer === 2 && inner === 3) {
await Promise.resolve();
break;
}
total += outer * 10 + inner;
}
}
while (enabled) {
if (total > 0) {
const label: string = await Promise.resolve<string>("selected");
await Promise.resolve<void>();
total += await Promise.resolve<i32>(7);
print(label);
break;
} else {
const value: i32 = await Promise.resolve<i32>(9);
await Promise.resolve<void>();
total += value;
break;
}
}
return total;
}Error Handling
Use try/catch/finally to handle async rejections.
When a suspending finally, including one nested recursively inside loops and branches, is entered with a pending return, break, continue, or throw, the async frame preserves that completion until cleanup finishes. A completion produced inside finally replaces the pending one, and rejection from an awaited cleanup operation takes precedence. Each finally executes exactly once.
error
async function riskyOperation(): Promise<string> {
const error: Error = { message: "network timeout", code: "ERR_NETWORK_TIMEOUT" };
throw error;
}
async function completeAfterCleanup(): Promise<i32> {
try {
return 42;
} catch (error: Error) {
return 0;
} finally {
await Promise.resolve();
print("cleanup before return");
}
}
async function main(): Promise<void> {
try {
const result: string = await riskyOperation();
print(result); // "result value"
} catch (error: Error) {
printError(error.message); // "network timeout"
} finally {
print("cleanup complete");
}
print(await completeAfterCleanup()); // 42
}A throw inside an async function rejects its returned Promise.
error
interface ValueError extends Error {
code: string;
}
async function validate(value: i32): Promise<i32> throws ValueError {
if (value < 0) {
const error: ValueError = { message: "value must be non-negative", code: "ERR_VALUE_MUST_BE_NON_NEGATIVE" };
throw error;
}
return value;
}
async function main(): Promise<void> {
try {
const result: i32 = await validate(-1);
} catch (error: Error) {
printError(error.message); // "value must be non-negative"
}
}AggregateError
When multiple operations fail, AggregateError groups all rejection reasons.
error
async function main(): Promise<void> {
try {
await Promise.reject<i32>({
message: "multi failure",
});
} catch (error: Error) {
printError(error.message); // "multi failure"
}
}Promise.resolve and Promise.reject
Create resolved or rejected promises directly.
Promise.resolve<T>(value: T): Promise<T>Promise.reject<T>(reason: Error): Promise<T>async function main(): Promise<void> {
const resolved: Promise<i32> = Promise.resolve(42);
const value: i32 = await resolved;
print(value); // 42
try {
const rejected: Promise<i32> = Promise.reject<i32>({ message: "boom", code: "ERR_BOOM" });
await rejected;
} catch (error: Error) {
printError(error.message); // "boom"
}
}Promise.all
Wait for all promises to resolve. Rejects immediately if any promise rejects.
Promise.all<T>(values: Promise<T>[]): Promise<T[]>async function loadUsers(): Promise<string[]> {
return ["Ada", "Grace"];
}
async function loadScores(): Promise<i32[]> {
return [95, 87];
}
async function main(): Promise<void> {
const [users, scores] = await Promise.all<string[] | i32[]>([
loadUsers(),
loadScores(),
]);
print(users); // ["Ada", "Grace"]
print(scores); // [95, 87]
}Promise.allSettled
Wait for all promises to settle (resolve or reject). Never rejects.
Promise.allSettled<T>(values: Promise<T>[]): Promise<PromiseSettledResult<T>[]>async function main(): Promise<void> {
const results: PromiseSettledResult<i32>[] = await Promise.allSettled<i32>([
Promise.resolve(42),
Promise.reject<i32>({ message: "expected failure", code: "ERR_EXPECTED_FAILURE" }),
]);
for (const result of results) {
if (result.status === "fulfilled") {
print(`resolved: ${result.value}`); // "resolved: 42"
} else {
print(`rejected: ${result.reason.message}`); // "rejected: expected failure"
}
}
}Promise.race
Resolves or rejects with the first settled promise.
Promise.race<T>(values: Promise<T>[]): Promise<T>import { sleepAsync } from "tyrus:task";
async function fastService(): Promise<string> {
await sleepAsync(5);
return "fast-result";
}
async function slowService(): Promise<string> {
await sleepAsync(50);
return "slow-result";
}
async function main(): Promise<void> {
const winner: string = await Promise.race<string>([
fastService(),
slowService(),
]);
print(winner); // "fast-result"
}This example uses sleepAsync to model different response times and targets the native runtime. The Playground's WASM runtime does not support async execution or Promise combinators yet.
Promise.any
Resolves with the first successful promise. Rejects only if all promises reject.
Promise.any<T>(values: Promise<T>[]): Promise<T>async function primarySource(): Promise<string> {
const error: Error = { message: "primary down", code: "ERR_PRIMARY_DOWN" };
throw error;
}
async function fallbackSource(): Promise<string> {
return "fallback-result";
}
async function main(): Promise<void> {
const result: string = await Promise.any<string>([
primarySource(),
fallbackSource(),
]);
print(result); // "fallback-result"
}Promise.withResolvers
Create a promise with external resolve and reject functions.
Promise.withResolvers<T>(): { promise: Promise<T>, resolve: (value: T) => void, reject: (reason: Error) => void }function createDeferred(): Promise<string> {
const { promise, resolve, reject } = Promise.withResolvers<string>();
resolve("done");
return promise;
}
async function main(): Promise<void> {
const result: string = await createDeferred();
print(result); // "done"
}then, catch, and finally
Chain promise continuations without await.
async function main(): Promise<void> {
Promise.resolve(42)
.then((value: i32) => {
print(value); // 42
})
.catch((error: Error) => {
printError(error.message);
})
.finally(() => {
print("settled");
});
}Cooperative Cancellation
Use cancel from tyrus:task to cooperatively cancel a pending promise.
import { cancel, sleepAsync } from "tyrus:task";
async function longRunning(): Promise<string> {
await sleepAsync(5000);
return "done";
}
async function main(): Promise<void> {
const pending: Promise<string> = longRunning();
const wasCancelled: boolean = cancel(pending, "user abort");
print(wasCancelled); // true
try {
const result: string = await pending;
} catch (error: Error) {
printError(error.message); // "user abort"
}
}Sleep
Delay execution without blocking the executor thread.
import { sleepAsync } from "tyrus:task";
async function countdown(): Promise<void> {
for (let i: i32 = 3; i > 0; i -= 1) {
print(i);
await sleepAsync(1000);
}
print("go!");
}
async function main(): Promise<void> {
await countdown();
}Promise Combinators in Practice
import { sleepAsync } from "tyrus:task";
interface TimeoutError extends Error {
code: string;
}
async function fetchWithTimeout(url: string, timeoutMs: u64): Promise<string> throws TimeoutError {
const fetchOp = async (): Promise<string> => {
// Simulated fetch
return `data from ${url}`;
};
const timeoutOp = async (): Promise<string> throws TimeoutError => {
await sleepAsync(timeoutMs);
const error: TimeoutError = { message: `timeout after ${timeoutMs}ms`, code: "ERR_TIMEOUT" };
throw error;
};
return await Promise.race<string>([fetchOp(), timeoutOp()]);
}
async function main(): Promise<void> {
try {
const data: string = await fetchWithTimeout("api.example.com", 5000);
print(data); // "data from api.example.com"
} catch (error) {
printError(error.message);
}
}Awaiting Once
A Promise<T> is consumed by await. The runtime holds one reference to it, and await takes that reference and releases it, so awaiting the same binding twice is a compile error (E3006) rather than a second read of a settled value:
error
async function value(): Promise<i32> {
return 7;
}
async function main(): Promise<void> {
const pending = value();
const first = await pending;
const second = await pending;
print(first + second);
}error[async-promise-already-awaited]: `pending` was already consumed by an earlier `await`; a `Promise<T>` can only be awaited once
at /src/main.tyr:8:26
const second = await pending;
^^^^^^^
help: store the awaited value in a binding and read that instead of awaiting `pending` againBind the awaited value and read the binding instead. The same rule applies to JoinHandle<T> and .join().
Error Examples
Async function must return Promise
An async function that returns a non-Promise type is a compile error:
async function bad(): i32 {
return 42;
}error[async-missing-promise-return]: async function must return `Promise<T>`, found `i32`
at /src/main.tyr:1:23
async function bad(): i32 {
^^^
help: change the return type to `Promise<i32>`Discarded Promise
A Promise that is not awaited, returned, or stored produces a warning:
async function fetchData(): Promise<i32> {
return 42;
}
async function main(): Promise<void> {
fetchData();
}warning[E3005]: promise not consumed
--> src/main.tyr:6:5
|
6 | fetchData();
| ^^^^^^^^^^
|
help: await the promise, return it, or store it for later awaitawait outside async
Using await outside an async function is a compile error:
async function getData(): Promise<i32> {
return 42;
}
function sync(): void {
const value: i32 = await getData();
}error[async-await-outside-async]: `await` can only be used inside an async function
at /src/main.tyr:6:24
const value: i32 = await getData();
^^^^^
help: move this `await` into an `async` function or mark its enclosing function `async`