Async e Await
tyrus suporta funções async executáveis, expressões await, valores nativos Promise<T> e tratamento estruturado de rejeições.
Funções Async
Declare uma função async com a palavra-chave async. Ela retorna uma Promise<T> que resolve para o tipo interno.
async function fetchUser(): Promise<string> {
return "Ada";
}
async function main(): Promise<void> {
const name: string = await fetchUser();
print(name); // "Ada"
}Uma função async void retorna Promise<void> e não carrega um 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
Uma async function main(): Promise<void> sem parâmetros pode suspender em múltiplas instruções await no nível superior.
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"
}Funções Arrow Async
Funções arrow async seguem a mesma sintaxe.
const fetchData = async (): Promise<i32> => {
return 42;
};
async function main(): Promise<void> {
const value: i32 = await fetchData();
print(value); // 42
}Objetos mutáveis através de await
Um objeto mutável cujos campos obrigatórios armazenados sejam todos valores Copy pode permanecer vivo através de suspensões. Seus campos Copy podem ser alterados in-place, e o binding inteiro pode ser substituído por outro literal de objeto compatível.
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);
}Objetos mutáveis com campos heap-owned suportados podem ser substituídos integralmente ou atualizados campo a campo. A atribuição a campos string, array, optional e objetos aninhados avalia e clona profundamente o substituto antes de liberar o campo anterior, portanto atribuições derivadas do próprio valor permanecem válidas. Métodos mutáveis de campos de array de strings, como push, splice, fill e sort, operam diretamente no campo pertencente ao frame. Cada local recursivamente owned carrega um bit de inicialização, e o drop glue tipado gerado libera somente valores inicializados exatamente uma vez durante substituição ou destruição do frame.
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);
}Fluxo de controle aninhado
Suspensões podem aparecer através de blocos, ramos condicionais, laços, switches e tratamento estruturado de erros arbitrariamente aninhados. A máquina de estados assíncrona preserva as instâncias de laço ativas e os escopos léxicos entre caminhos irmãos com suspensão, portanto break, continue, bindings locais de ramo e instruções antes ou depois de cada suspensão mantêm seu comportamento normal. Ambos os ramos de um if aninhado podem conter cadeias de suspensão independentes com tamanhos, tipos de payload e bindings diferentes; a condição é avaliada uma única vez.
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;
}Tratamento de Erros
Use try/catch/finally para tratar rejeições async.
Quando um finally suspensivo, inclusive um aninhado recursivamente dentro de laços e ramos, é iniciado com um return, break, continue ou throw pendente, o frame assíncrono preserva essa completion até o fim do cleanup. Uma completion produzida dentro do finally substitui a pendente, e a rejeição de uma operação de cleanup aguardada tem precedência. Cada finally executa exatamente uma vez.
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
}Um throw dentro de uma função async rejeita a Promise retornada.
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
Quando múltiplas operações falham, AggregateError agrupa todos os motivos de rejeição.
error
async function main(): Promise<void> {
try {
await Promise.reject<i32>({
message: "multi failure",
});
} catch (error: Error) {
printError(error.message); // "multi failure"
}
}Promise.resolve e Promise.reject
Crie promises resolvidas ou rejeitadas diretamente.
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
Aguarda todas as promises resolverem. Rejeita imediatamente se qualquer promise rejeitar.
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
Aguarda todas as promises se estabelecerem (resolverem ou rejeitarem). Nunca rejeita.
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
Resolve ou rejeita com a primeira promise que se estabelecer.
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
Resolve com a primeira promise bem-sucedida. Rejeita apenas se todas as promises rejeitarem.
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
Crie uma promise com funções externas de resolve e reject.
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 e finally
Encadeie continuações de promise sem await.
async function main(): Promise<void> {
Promise.resolve(42)
.then((value: i32) => {
print(value); // 42
})
.catch((error: Error) => {
printError(error.message);
})
.finally(() => {
print("settled");
});
}Cancelamento Cooperativo
Use cancel de tyrus:task para cancelar cooperativamente uma promise pendente.
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
Atrasa a execução sem bloquear o thread do executor.
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 na Prática
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);
}
}Aguardando Uma Vez
Uma Promise<T> é consumida pelo await. O runtime mantém uma única referência a ela, e o await toma essa referência e a libera, então aguardar o mesmo binding duas vezes é erro de compilação (E3006) e não uma segunda leitura de um valor já resolvido:
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` againGuarde o valor aguardado num binding e leia o binding. A mesma regra vale para JoinHandle<T> e .join().
Exemplos de Erro
Função async deve retornar Promise
Uma função async que retorna um tipo não-Promise é erro de compilação:
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>`Promise descartada
Uma Promise que não é aguardada, retornada ou armazenada produz um 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 fora de async
Usar await fora de uma função async é erro de compilação:
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`