Elixir Expert · Lesson 1 · On the house

Task.async and await

Task.async/1, Task.await/2, timeouts, linking vs unsupervised. Lesson 1 is free — on the house.

Lessons · Elixir Expert · Lesson 1 of 10 · On the house

Task.async and await

Task.async/1, Task.await/2, timeouts, linking vs unsupervised.

Illustration for Elixir
Lesson 1 is on the house.

Task.async(fun) starts a linked process that runs fun and returns a %Task{} struct. The caller is linked: if the task crashes with an uncaught exit, the caller can crash too (unless trapping exits).

Task.await(task, timeout \\ 5000) blocks until the task finishes or the timeout (milliseconds) elapses. On success it returns the fun's result. On timeout it exits the caller with {:timeout, {Task, :await, ...}} and also exits the task.

Task.yield(task, timeout) is gentler: it returns {:ok, result}, {:exit, reason}, or nil on timeout without killing the caller. After a nil yield you can Task.shutdown(task) or await again.

Linking is the default for async. For fire-and-forget work you do not want tied to the caller's life, prefer Task.Supervisor.async_nolink/2 (next lesson) or Task.start/1 (unlinked, no await struct).

Misses: awaiting forever with :infinity on a stuck task, ignoring that await exits on timeout, or spawning raw spawn when you needed a Task you can await.

task-async-await

task =
  Task.async(fn ->
    Process.sleep(50)
    21 * 2
  end)

result = Task.await(task, 1_000)
IO.inspect(result)

yielded =
  Task.async(fn -> :ok end)
  |> Task.yield(500)

IO.inspect(yielded)
Match this when you type.

Quiz

What does Task.async/1 return?

Quiz

What happens if Task.await times out?

Quiz

How does Task.yield differ from await on timeout?

Quiz

Are Task.async processes linked by default?

Check

Match the still for: Task.async and await.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.