🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Tasks

A task is a process started to do one job and report its result back. Task.async starts the job, and Task.await collects its answer.

Await returns the task result

The task multiplies 6 by 7 on its own. Await collects the value its function returned.

task = Task.async(fn -> 6 * 7 end)
IO.puts(Task.await(task))

Two tasks awaited in order

Both tasks start before either is awaited. Awaiting the first task first prints its result first.

first = Task.async(fn -> 3 * 10 end)
second = Task.async(fn -> 4 * 3 end)
IO.puts(Task.await(first))
IO.puts(Task.await(second))

Awaited results combine like values

Each await returns a plain number. The two numbers add together in one expression.

left = Task.async(fn -> 9 * 5 end)
right = Task.async(fn -> 11 * 5 end)
IO.puts(Task.await(left) + Task.await(right))

Example

word_task = Task.async(fn -> String.upcase("elixir") end)
length_task = Task.async(fn -> String.length("elixir") end)
IO.puts("#{Task.await(word_task)} has #{Task.await(length_task)} letters")

Key points

  • Start: Task.async(fun) starts a task running the given anonymous function.
  • Await: Task.await(task) waits for the task to finish and returns the value its function returned.
  • Handle: the value Task.async returns names the task, and you hand it to Task.await to get the result.
  • Together: a program can start several tasks first and await each one when it needs the answers.
  • Answer order: awaiting tasks in a chosen order gives their results in that order, whichever task finishes first.
  • One job: a task suits a single piece of work that produces one result.

In this example, one task uppercases the word elixir while another counts its letters. The last line awaits both tasks and builds the sentence from their two results.

Note

a task is built on a process, with await added as the way to collect the result.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Task.await(task) return?