Production Track ยท 04

Async, concurrency & resource scopes

PeaLang has two execution faces: the interpreter for everyday scripting and the bytecode VM for portable, bounded execution. Cooperative async runs on the AsyncVirtualMachine; structured concurrency and cancellation are provided by dedicated namespaces.

Async syntax

async function fetch_user(id) {
  await sleep(0.01)
  return {"id": id, "name": "user-{id}"}
}

async function load_dashboard() {
  let jobs = [fetch_user(1), fetch_user(2)]
  let users = await concurrency.gather(jobs)
  return {"users": users, "count": len(users)}
}

concurrency exposes sleep, spawn, gather, timeout, result and cancel in the async VM namespace. Structured task groups add cancellation scopes and first-exception semantics.

Deadlines and cancellation

async function with_deadline() {
  return await concurrency.timeout(1.5, api.fetch("slow"))
}

Always impose a deadline on network steps. Cancellation is cooperative: a token is checked between VM instructions, and task groups cancel pending children when one task fails.

Parallel expression

let together = parallel {
  cpu_task()
  io_task()
}

parallel is a real parser construct producing ParallelExpr. Use it for independent calls when the host allows parallel scheduling; do not assume deterministic ordering of side effects.

Resource scopes

using conn = open_connection() {
  print conn.query("select 1")
}

print scopes.current()
print scopes.snapshot()
scopes.dispose()

The v3.1.36 tag is the resource-scopes release. Resource scopes give bounded child budgets and deterministic disposal; open_connection must be supplied by the embedding host. This is the right boundary for database handles, file descriptors and network sessions.

Choosing the runtime

NeedRuntimeNotes
Rich expressions, interpolation, quick iterationpea run (interpreter)Full expression support.
Portable artifact, instruction budgets, sandboxpea compile + pea vmNarrower expression set; use plain concatenation.
Cooperative async with cancellationAsyncVirtualMachine / AsyncVMRuntimeRegister host async functions, call exported async functions.
Browser / cross-runtime deliverypea wasm-buildProduces a PEAWASM artifact from bytecode.
Async and resource scopes are labelled Preview in pealang/compatibility.py even though the syntax exists. Pin the runtime version and gate them in CI before depending on them in production.

See the LLM workflow examples and resilience examples for complete async patterns.