Sub topic 4
Using .await to Get a Result
This chapter assumes you can write async fn and async blocks (previous chapter), know that a future is a value implementing Future, and have Tokio in Cargo.toml with the full feature. Here you learn what .await does, where it is allowed, and the mistakes it causes most often.
What .await does
An async fn returns a future, not its result. .await turns that future into the value it produces. Writing work(1, 100).await means: poll this future until it is ready, then use its output as the value of this expression.
The behavior depends on what poll returns:
| Poll result | Effect on the awaiting code |
|---|---|
| `Poll::Ready(value)` | The `.await` expression evaluates to `value`, and execution continues on the next line. |
| `Poll::Pending` | The current async function suspends and returns `Pending` to whoever polled it. The thread is free to run other tasks. |
When the future's waker fires, the executor polls the task again. Execution resumes at the same .await, with all local variables intact.
The key point is that .await suspends the current task, not the thread. Other tasks can run on that thread while this one waits.
Where .await is allowed
You can write .await only inside an async fn, an async block, or an async closure. A plain fn has no way to suspend, so the compiler rejects .await there. A regular closure is its own function, so .await inside |x| { ... } also fails, even when the closure sits inside an async function. Return an async block from the closure instead: |x| async move { work(x, 10).await }.
To enter async code from synchronous code, you need a runtime. #[tokio::main] does this for main. You can also build one by hand and call block_on:
use std::time::Duration;
use tokio::time::sleep;
async fn work(id: u32, ms: u64) -> u32 {
sleep(Duration::from_millis(ms)).await;
id
}
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
let id = rt.block_on(async { work(1, 10).await });
println!("{id}");
}Do not call block_on from inside async code. It blocks the worker thread, and Tokio panics if you try it within a runtime.
Sequential by default
Each .await finishes before the next line runs. Awaiting two futures one after another does not run them at the same time.
use std::time::{Duration, Instant};
use tokio::time::sleep;
async fn work(id: u32, ms: u64) -> u32 {
sleep(Duration::from_millis(ms)).await;
id
}
#[tokio::main]
async fn main() {
let start = Instant::now();
let a = work(1, 200).await;
let b = work(2, 100).await;
println!("{a} {b} after {} ms", start.elapsed().as_millis());
}This prints about 300 ms, because the second call does not start until the first returns. The async code is non-blocking, but it is still ordered. To overlap the waits, you use join! or spawned tasks, which a later chapter covers.
Awaiting inside larger expressions
.await is a postfix operator, so it chains with method calls and ?. It binds like a field access, which is why this reads left to right:
use std::error::Error;
use tokio::fs;
async fn total_len(paths: &[&str]) -> Result<usize, Box<dyn Error>> {
let mut total = 0;
for p in paths {
total += fs::read(p).await?.len();
}
Ok(total)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let n = total_len(&["Cargo.toml"]).await?;
println!("{n} bytes");
Ok(())
}Read fs::read(p).await?.len() in order:
fs::read(p)creates the future..awaitproduces anio::Result<Vec<u8>>.?returns early fromtotal_lenon error, or unwraps theVec<u8>..len()is called on that vector.
Because total_len is itself async, the early return becomes the error output of its future. The caller then needs its own .await and its own ?.
Common errors
Forgetting .await
Without .await, you hold a future instead of its output. The compiler usually catches this, because u32 and impl Future<Output = u32> are different types. A statement like work(1, 10); compiles but triggers an unused_must_use warning. The future was created and then dropped without running, so nothing happened. Treat that warning as a bug.
use std::time::Duration;
use tokio::time::sleep;
async fn work(id: u32, ms: u64) -> u32 {
sleep(Duration::from_millis(ms)).await;
id
}
#[tokio::main]
async fn main() {
let fut = work(1, 10);
let n: u32 = fut.await;
println!("{}", n + 1);
}Expecting .await to yield control
Awaiting while holding a value that cannot cross the suspension
Everything alive at an .await is stored in the future, so it must live as long as the task does. Holding a std::sync::MutexGuard or an Rc across an .await can make the future not Send. That is an error when you pass it to tokio::spawn. Drop such values before the .await, or use async-aware types. Later chapters return to this.
Awaiting the same future twice
.await consumes the future by value, so you cannot await a future again after it completes. To run the work twice, call the async function twice.
Exercise
A function runs let a = fetch_a().await; let b = fetch_b().await;. Each call takes 100 ms. Why does the function take about 200 ms, and does the thread sit idle during that time?
Show answer
The second .await line does not start until the first completes, so the waits add up to about 200 ms. The thread is not idle. While each task is suspended on Pending, the executor can run other tasks on it. This code just does not overlap its own two operations.
Exercise
You write let v = fs::read("data.txt")?; inside an async fn returning io::Result<Vec<u8>>, and the compiler complains. What is missing, and what is the correct line?
Show answer
? is applied to a future instead of a Result, because .await is missing. The correct line is let v = fs::read("data.txt").await?;.