Skip to content

Async ​

async fn and await ​

Calling an async fn does not run the body; it starts a task (task). await waits for it and returns the value.

mzs
async fn double(n) { n * 2 }

t = double(21)
type(t)  # → "task"
t.await  # → 42
t.done  # → true
await(double(5))  # → 10

The body starts running when the calling code lets go of the interpreter: on await, sleep or in a blocking call such as an HTTP request.

mzs
async fn work() { println("task body") }
t = work()
println("call returned")
t.await
text
call returned
task body

Task methods ​

MethodWhat it does
t.awaitwaits and returns the value; the task's error is raised here
t.donewhether it has finished — does not wait
t.timeout(d)await, but no longer than d seconds; the task keeps running
t.cancelstops the task
mzs
async fn slow() { sleep(0.3); "done" }

t = slow()
try t.timeout(0.05) else (e) -> e["kind"]  # → "timeout"
t.await  # → "done"

t2 = slow()
t2.cancel
try t2.await else (e) -> e["kind"]  # → "canceled"

In parallel ​

Start all the tasks first, then wait. Waiting inside the same map runs them one by one.

mzs
include http

urls = ["https://example.com/a", "https://example.com/b"]
async fn get(url) { http.get(url)["body"] }

pages = urls.map { get(it) }.map { it.await }  # in parallel
pages = urls.map { get(it).await }  # one by one

sleep ​

sleep(d) waits d seconds (fractions allowed) and lets go of the interpreter: while one task sleeps, others run.

mzs
log = []
async fn nap(id, d) { sleep(d); log.push(id) }

ts = [nap("slow", 0.2), nap("fast", 0.05)]
ts.map { it.await }
log  # → ["fast","slow"]

tasks.all and tasks.race ​

Needs include tasks.

FunctionWhat it does
tasks.all(ts)waits for all tasks; values in array order
tasks.race(ts)returns the value of the first to finish, cancels the rest
mzs
include tasks

async fn nap(n) { sleep(n / 20.0); n }
tasks.all([3, 1, 2].map { nap(it) })  # → [3,1,2]

async fn mirror(name, d) { sleep(d); name }
tasks.race([mirror("london", 1), mirror("berlin", 0.05)])  # → "berlin"

An error in any task is raised at the call site:

mzs
include tasks

async fn ok() { 1 }
async fn bad() { raise("failure") }
try tasks.all([ok(), bad()]) else (e) -> e["message"]  # → "failure"

Anonymous ​

mzs
f = async fn(n) { n * 2 }
f(21).await  # → 42

There are no async { … } closures — only async fn.

Worth knowing ​

  • Only one task runs at a time: switching happens only on waits. So shared arrays and dicts need no protection.
  • The order in which tasks get control is not guaranteed.
  • Tasks spend the script's shared step and time budget.
  • The number of unfinished tasks at once is limited (64 by default).
  • A task without await still runs to the end; its error does not reach any value (in the terminal it is printed to stderr). To catch the error, wait for the task.