Skip to content

Async y Await ​

tyrus admite funciones async ejecutables, expresiones await, valores nativos Promise<T> y manejo estructurado de rechazos.

Funciones Async ​

Declara una función async con la palabra clave async. Retorna un Promise<T> que se resuelve al tipo interno.

tyrus
async function fetchUser(): Promise<string> {
    return "Ada";
}

async function main(): Promise<void> {
    const name: string = await fetchUser();
    print(name); // "Ada"
}

Una función async con retorno void retorna Promise<void> y no porta un payload.

tyrus
async function logMessage(message: string): Promise<void> {
    print(message); // "hello from tyrus"
}

async function main(): Promise<void> {
    await logMessage("hello from tyrus");
}

Await de nivel superior ​

Una async function main(): Promise<void> sin parámetros puede suspenderse en múltiples declaraciones await de nivel superior.

tyrus
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"
}

Funciones flecha async ​

Las funciones flecha async siguen la misma sintaxis.

tyrus
const fetchData = async (): Promise<i32> => {
    return 42;
};

async function main(): Promise<void> {
    const value: i32 = await fetchData();
    print(value); // 42
}

Objetos mutables a través de await ​

Un objeto mutable cuyos campos almacenados obligatorios sean todos valores Copy puede permanecer vivo a través de suspensiones. Sus campos Copy se pueden modificar in-place, y el binding completo se puede reemplazar por otro literal de objeto compatible.

tyrus
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);
}

Los objetos mutables con campos heap-owned compatibles pueden reemplazarse por completo o actualizarse campo por campo. La asignación a campos string, array, optional y objetos anidados evalúa y clona profundamente el reemplazo antes de liberar el campo anterior, por lo que las asignaciones derivadas del propio valor siguen siendo válidas. Los métodos mutables de campos de arrays de strings, como push, splice, fill y sort, operan directamente sobre el campo poseído por el frame. Cada local recursivamente owned lleva un bit de inicialización, y el drop glue tipado generado libera solo los valores inicializados exactamente una vez durante el reemplazo o la destrucción del frame.

tyrus
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);
}

Flujo de control anidado ​

Las suspensiones pueden aparecer a través de bloques, ramas condicionales, bucles, switches y manejo estructurado de errores anidados arbitrariamente. La máquina de estados asíncrona conserva las instancias de bucle activas y los ámbitos léxicos entre rutas hermanas con suspensión, por lo que break, continue, los bindings locales de rama y las instrucciones anteriores o posteriores a cada suspensión mantienen su comportamiento normal. Ambas ramas de un if anidado pueden contener cadenas de suspensión independientes con distintas longitudes, tipos de payload y bindings; la condición se evalúa una sola vez.

tyrus
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;
}

Manejo de errores ​

Usa try/catch/finally para manejar rechazos async.

Cuando un finally suspensivo, incluido uno anidado recursivamente dentro de bucles y ramas, comienza con un return, break, continue o throw pendiente, el frame asíncrono conserva esa completion hasta que termina el cleanup. Una completion producida dentro de finally reemplaza la pendiente, y el rechazo de una operación de cleanup esperada tiene prioridad. Cada finally se ejecuta exactamente una vez.

error

tyrus
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
}

Un throw dentro de una función async rechaza el Promise que retorna.

error

tyrus
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 ​

Cuando múltiples operaciones fallan, AggregateError agrupa todas las razones de rechazo.

error

tyrus
async function main(): Promise<void> {
    try {
        await Promise.reject<i32>({
            message: "multi failure",
        });
    } catch (error: Error) {
        printError(error.message); // "multi failure"
    }
}

Promise.resolve y Promise.reject ​

Crea promises resueltos o rechazados directamente.

FirmaPromise.resolve<T>(value: T): Promise<T>
FirmaPromise.reject<T>(reason: Error): Promise<T>
tyrus
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 ​

Espera a que todos los promises se resuelvan. Rechaza inmediatamente si algún promise se rechaza.

FirmaPromise.all<T>(values: Promise<T>[]): Promise<T[]>
tyrus
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 ​

Espera a que todos los promises se resuelvan o rechacen. Nunca rechaza.

FirmaPromise.allSettled<T>(values: Promise<T>[]): Promise<PromiseSettledResult<T>[]>
tyrus
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 ​

Resuelve o rechaza con el primer promise que se resuelva.

FirmaPromise.race<T>(values: Promise<T>[]): Promise<T>
tyrus
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 ​

Resuelve con el primer promise exitoso. Rechaza solo si todos los promises se rechazan.

FirmaPromise.any<T>(values: Promise<T>[]): Promise<T>
tyrus
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 ​

Crea un promise con funciones externas de resolve y reject.

FirmaPromise.withResolvers<T>(): { promise: Promise<T>, resolve: (value: T) => void, reject: (reason: Error) => void }
tyrus
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 y finally ​

Encadena continuaciones de promise sin await.

tyrus
async function main(): Promise<void> {
    Promise.resolve(42)
        .then((value: i32) => {
            print(value); // 42
        })
        .catch((error: Error) => {
            printError(error.message);
        })
        .finally(() => {
            print("settled");
        });
}

Cancelación cooperativa ​

Usa cancel de tyrus:task para cancelar cooperativamente un promise pendiente.

tyrus
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 ​

Retrasa la ejecución sin bloquear el hilo executor.

tyrus
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();
}

Combinadores de Promise en la práctica ​

tyrus
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);
    }
}

Esperando Una Vez ​

Una Promise<T> es consumida por el await. El runtime mantiene una única referencia a ella, y el await toma esa referencia y la libera, así que esperar el mismo binding dos veces es un error de compilación (E3006) y no una segunda lectura de un valor ya resuelto:

error

tyrus
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);
}
text
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` again

Guarda el valor esperado en un binding y lee el binding. La misma regla aplica a JoinHandle<T> y .join().

Ejemplos de Error ​

La función async debe retornar Promise

Una función async que retorna un tipo que no es Promise es un error de compilación:

tyrus
async function bad(): i32 { 
    return 42;
}
text
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>`

Promise descartado

Un Promise que no se espera, retorna ni almacena produce una advertencia:

tyrus
async function fetchData(): Promise<i32> {
    return 42;
}

async function main(): Promise<void> {
    fetchData(); 
}
text
warning[E3005]: promise not consumed
  --> src/main.tyr:6:5
   |
 6 |     fetchData();
   |     ^^^^^^^^^^
   |
help: await the promise, return it, or store it for later await

await fuera de async

Usar await fuera de una función async es un error de compilación:

tyrus
async function getData(): Promise<i32> {
    return 42;
}

function sync(): void {
    const value: i32 = await getData(); 
}
text
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`