Async & Concurrency Reference
Kyna integrates asynchronous operations directly into the language through async function definitions and the await prefix expression.
Asynchronous Functions: async fn
Functions that perform non-blocking operations such as networking, disk I/O, or timers are declared with async fn:
async fn fetchUserProfile(userId: int): str {
const url = "https://api.kyna.dev/users/" + userId;
const raw = await fetch(url, { timeout: 5000 });
return raw;
}
Awaiting Values: await
The await keyword pauses evaluation of the current asynchronous execution flow until the target operation resolves, without blocking other concurrent tasks on the runtime event loop:
async fn main() {
print("Initiating requests...");
const userPromise = await fetchUserProfile(42);
print("Profile received:", userPromise);
}
await main();
Error Handling in Async Contexts
Async operations use standard try / catch blocks to capture timeouts, DNS resolution failures, and rejected network requests:
async fn safeFetch(url: str): str? {
try {
const response = await fetch(url, { timeout: 3000 });
return response;
} catch (err) {
print("Async fetch failed with code:", err.code);
print("Message:", err.message);
return null;
}
}
Concurrency Patterns & Best Practices
- Explicit Timeouts: Always specify a
timeoutoption (in milliseconds) when callingfetch()to prevent infinite hangs. - Graceful Degradation: Pair nullable returns (
T?) withtry/catcharound network borders to handle offline conditions safely. - Structured Logging: Log request duration by capturing
time.nowMs()before and afterawaitcalls.