Sub topic 4
What async fn and .await actually produce
This chapter assumes you know ownership and borrowing, traits and generics, enums, and how to write simple async fn code. It also assumes you have seen the Future trait and Poll from earlier chapters.
An async fn returns a future
An async fn does not run its body when you call it. It returns a value that implements Future, and the body runs only when something polls that value.
async fn add(a: u32, b: u32) -> u32 {
a + b
}
async fn run() -> u32 {
let x = add(1, 2).await;
x * 2
}The signature async fn add(a: u32, b: u32) -> u32 is roughly sugar for this:
use std::future::Future;
fn add(a: u32, b: u32) -> impl Future<Output = u32> {
async move { a + b }
}The return type is an anonymous type created by the compiler. You cannot write its name. You can only say that it implements Future<Output = u32>.
Async blocks
An async block produces a future in the same way, without a function around it. Arguments and captured variables are moved or borrowed into the future when you create it. That is why async move is common when a future must outlive the scope that built it.
What .await does
.await is only allowed inside an async context. On a future f, it behaves like this loop:
- Poll
fwith the current task'sContext. - If the result is
Poll::Ready(value), the.awaitexpression evaluates tovalue. - If the result is
Poll::Pending, the enclosing future also returnsPoll::Pendingto its own caller. The next poll resumes at the same.await.
So .await does not block the thread. It hands control back up the chain of futures until the executor, and it resumes from the same point on the next poll.
Common errors
- Forgetting to await. Calling
add(1, 2)and ignoring the result does nothing. The compiler warns that futures do nothing unless polled (unused_must_use). - Assuming work starts at the call. Any side effect in the body, such as sending a request, happens only after the first poll.
- Using
.awaitin a non-async function. This is a compile error. Either make the function async, or drive the future with an executor such asblock_on.
Exercise
What does let f = add(1, 2); do in a function where add is an async fn, and when does the body of add run?
Show answer
It creates a future and stores it in f. The body of add has not run. It runs when f is polled, for example by .await inside another async function or by an executor, and the result is 3 when it completes.