Sub topic 3
Using .await to get a result
This chapter assumes you can read async fn and async blocks, and that you know a future is a value that produces its result later. It also assumes you have Tokio set up with the full feature. Here you will learn what .await does, where you can use it, and which mistakes to watch for.
What .await does
.await is a postfix operator on a future. It does two things:
- It polls the future. If the future is
Ready, the expression evaluates to the future's output. - If the future is
Pending, the current async function suspends and control returns to the executor, which runs other tasks. When the future's waker fires, the executor polls your function again and it resumes after the.await.
The suspension does not block the thread. Only the function containing the .await pauses. The thread keeps working on other tasks.
use std::time::Duration;
use tokio::time::sleep;
async fn fetch_user(id: u32) -> String {
sleep(Duration::from_millis(100)).await;
format!("user-{id}")
}
async fn fetch_score(name: &str) -> u32 {
sleep(Duration::from_millis(100)).await;
name.len() as u32
}
#[tokio::main]
async fn main() {
let user = fetch_user(1).await;
let score = fetch_score(&user).await;
println!("{user} scored {score}");
}The type of fetch_user(1) is an anonymous future. The type of fetch_user(1).await is String. The second call needs the first result, so the two waits happen in order and take about 200 ms.
Where .await is allowed
.await is valid only inside an async fn, an async block, or an async closure. Using it in a plain fn produces error E0728. The usual fix is to make the function async and .await it from its caller. At the top of the program, #[tokio::main] supplies the first async context.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `.await` | The compiler reports a type mismatch or `no method found` on `impl Future`, or warns that the future is unused | Add `.await` |
| `.await` in a non-async function | E0728 | Make the function `async` |
| Awaiting unrelated calls one after another | Correct output, but total time is the sum of the waits | Use `join!` (a later chapter) |
| Holding a `std::sync::MutexGuard` across `.await` | The task is no longer `Send`, so `tokio::spawn` rejects it | Drop the guard first, or use an async-aware lock |
Awaiting with ?
When the future's output is a Result, write .await? to wait and then propagate the error. The next chapters cover this in detail.
Exercise
In the example above, fetch_user(1) and fetch_score(&user) each sleep 100 ms. Why does main take about 200 ms instead of 100 ms, and what does .await do while each sleep is pending?
Show answer
The second call needs the user value produced by the first, and main does not start the second future until the first .await returns, so the waits add up to about 200 ms. While a sleep is pending, .await suspends main and returns control to the executor, which can run other tasks on the same thread. It does not block the thread.