Task
Task module: Elixir-style lightweight async tasks for one-off concurrent work.
Tasks provide a simple interface for running functions asynchronously without the ceremony of defining a full actor. They build on the task_spawn / task_await interpreter primitives (Phase 1: single-threaded cooperative scheduler — tasks execute eagerly at spawn time).
Basic usage:
let t = Task.async(fn () -> expensive_computation()) let result = Task.await(t) -- Ok(value) or Err(reason)
Parallel map:
let results = Task.async_stream([1, 2, 3], fn n -> n * n) -- results : List(Ok(Int) | Err(String)), in original order
Multiple tasks:
let t1 = Task.async(fn () -> fetch_user(1)) let t2 = Task.async(fn () -> fetch_user(2)) let [r1, r2] = Task.await_many([t1, t2])
Note on overloading: March does not support function overloading. Use await_ms/await_many_ms for explicit timeout variants. Use async_stream_n for a concurrency-capped parallel map.
Functions
Spawn f as a lightweight async task. f must be a zero-argument function: fn () -> result. Returns a Task handle that can be passed to Task.await.
Example: let t = Task.async(fn () -> 1 + 1) Task.await(t) -- Ok(2)
Await the result of a task with a default 5-second timeout. Returns Ok(result) or Err(reason).
Example: let t = Task.async(fn () -> 42) Task.await(t) -- Ok(42)
Await the result of a task with an explicit timeout in milliseconds. Returns Ok(result) or Err(reason). timeout_ms is accepted for API compatibility; enforcement requires the async runtime (Phase 2+).
Example: let t = Task.async(fn () -> slow_query()) Task.await_ms(t, 10000) -- wait up to 10 seconds
Unwrap the result of a task, raising on error. Returns the result value directly (not wrapped in Ok). Panics if the task failed.
Example: let t = Task.async(fn () -> 42) Task.await!(t) -- 42
Await all tasks, returning results in the same order as the input list. Each element is Ok(v) or Err(reason). Uses a default 5-second timeout per task.
Example: let t1 = Task.async(fn () -> 1) let t2 = Task.async(fn () -> 2) Task.await_many([t1, t2]) -- [Ok(1), Ok(2)]
Await all tasks with an explicit timeout in milliseconds. Returns results in the same order as the input list. Each element is Ok(v) or Err(reason).
Run f on each element of list concurrently, returning results in original order. Equivalent to a parallel Enum.map. Each result is Ok(v) or Err(reason).
Example: Task.async_stream([1, 2, 3], fn n -> n * n) -- [Ok(1), Ok(4), Ok(9)]
Run f on each element concurrently with a cap on parallel tasks. max_concurrency limits how many tasks run at once (advisory in Phase 1). Returns results in original order; each element is Ok(v) or Err(reason).
Example: Task.async_stream_n(urls, fn url -> http_get(url), 10)