Search⌘ K
AI Features

Use the await and yield Functions to Retrieve Results

Explore how to retrieve results from asynchronous tasks in Elixir using Task.await and Task.yield. Understand their differences in timeout handling and learn to manage task completion and errors in concurrent programming.

To retrieve the task result, we can use the Task.await/1 or the Task.yield/1 function. Both accept a Task struct as an argument. There is an essential difference in how await/1 and yield/1 work, so we have to choose wisely. They both stop the program and try to retrieve the task’s result. The difference comes from the way they handle process timeouts.

The await function

Process timeouts ensure that processes don’t get stuck waiting forever. Let’s increase the time of the send_email/1 function to 30 seconds:

Here is the executable command:

Scala
Task.async(fn -> Sender.send_email("hi@world.com") end) |> Task.await()

It will now run the code ...