PeaBox Lab › PeaLang › Learn › Chapter 13 › Lesson 1

Part III — Advanced Systems · Chapter 13 · Lesson 1 of 5 · 5 min read

Lesson 1: async Functions, await, and Cooperative Suspension

Lesson level: Advanced

Purpose: Learn how PeaLang expresses work that waits, how async and await suspend and resume execution, and why cooperative scheduling keeps programs predictable.

Release note: async syntax, standard-library names, and scheduler details in this lesson are illustrative. async and await are reserved keywords (Chapter 2); verify exact behaviour against your installed v0.63 release.

Learning objectives

By the end of this lesson, you should be able to:

1.1 Why asynchrony

Many tasks spend most of their time waiting: for an HTTP response, a database row, or a file read. If each wait blocks the whole program, ten independent lookups take ten times as long as one. Asynchrony lets the runtime start other work while one task waits.

1.2 Declaring an async function

async function fetch_tier(customer_id) {
  let record = await std.http.get_json("/customers/{customer_id}")
  return record["tier"]
}

Calling an async function does not run its body to completion. It returns a Future, the type introduced in Chapter 7, which represents a result that will be available later.

1.3 Awaiting a Future

async function reason_for_order(order) {
  let tier = await fetch_tier(order["customer_id"])
  if tier == "gold" and order["qty"] >= 10 { return "GOLD_BULK" }
  return "NONE"
}

await pauses the current async function until the Future completes, then evaluates to its value. If the Future failed, await raises the same error, so ordinary try/catch handling applies.

1.4 Where await is allowed

1.5 Suspension points

Each await is a suspension point. When the awaited Future is not ready, the function saves its frame, gives control back to the scheduler, and resumes at the same point later. Local variables keep their values across the pause.

1.6 Cooperative scheduling

PeaLang tasks yield only at suspension points. Between two awaits, a task runs without interruption from other PeaLang tasks. This makes reasoning simpler: shared values cannot change underneath you in the middle of a computation that contains no await.

PropertyConsequence
Yield only at awaitNo surprise interleaving inside synchronous code
A long loop without awaitOther tasks wait until it finishes
Many awaits on shared stateState may change between them; re-check it
Deterministic order for the same inputsEasier testing and replay

1.7 Sequential versus concurrent awaits

# Sequential: second lookup starts after the first finishes
let a = await fetch_tier("C-1")
let b = await fetch_tier("C-2")

# Concurrent: both lookups start, then both are awaited
let fa = fetch_tier("C-1")
let fb = fetch_tier("C-2")
let a = await fa
let b = await fb

Starting Futures before awaiting them lets their waits overlap. Lesson 4 replaces this manual pattern with task groups, which also handle failure and cancellation correctly.

1.8 Blocking inside async code

A synchronous call that waits, such as a blocking host function or a large CPU-bound loop, holds the scheduler. Every other task stalls until it returns. Prefer async versions of I/O operations, and split heavy computation or move it to the host.

1.9 Async and the interpreter versus VM

Both engines implement the same suspension semantics: the saved frame from Chapter 12 Lesson 5 is what lets a function resume after an await. Differential tests should therefore produce identical results and ordering for async programs as well.

1.10 Errors across await

async function safe_tier(id) {
  try {
    return await fetch_tier(id)
  } catch err {
    return "standard"
  }
}

An error raised by the awaited work appears at the await. Handle it where you can make a sensible decision, and let limit and permission errors propagate to the host.

1.11 Worked example

The order_rules service must look up the customer tier for each order before computing a reason. Making reason_for_order async lets the host process several orders while each tier lookup waits, without changing the GOLD_BULK, GOLD, BULK, and NONE rules.

1.12 Common mistakes

MistakeConsequenceFix
Calling an async function without awaitingResult is a Future, not a valueAwait it or pass it to a task group
Awaiting in a tight sequence by habitNo overlap; slowStart independent work first
Long synchronous loops in async codeStarves other tasksSplit work or move it to the host
Assuming state is unchanged after awaitStale decisionsRe-read shared state after resuming

1.13 Guided practice

1.14 Hands-on lab

Write an async price_orders that looks up tiers for five synthetic orders using a simulated host lookup with a fixed delay. Measure total time for sequential and concurrent versions and confirm identical results.

Deliverable: both versions, their timings, and a short explanation of the difference.

1.15 Review questions

1.16 Applied challenge

Identify three operations in your own domain that wait on external systems. Sketch an async design that overlaps them and explain which ordering guarantees you still need.

Lesson summary

Transition to Lesson 2

Most real waiting happens in the host: HTTP clients, databases, timers. Lesson 2 covers host awaitables and the boundary where PeaLang async code meets host async code.

Lesson status: Ready for review.

← Previous Next →