Sub topic 4
What async fn and .await actually produce
This chapter assumes you can write simple async fn code and call .await. It also assumes you know traits, generics, impl Trait return types, and basic lifetimes. The previous chapters covered the Future trait and Poll. Here you will see what the async and .await keywords turn into.
An async fn returns a future
An async fn does not run when you call it. The call 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
}The signature above is roughly equivalent to this ordinary function:
use std::future::Future;
fn add(a: u32, b: u32) -> impl Future<Output = u32> {
async move { a + b }
}The returned type is anonymous. You cannot write its name, but you can rely on two facts: it implements Future<Output = u32>, and it owns the arguments a and b.
The async move { ... } expression is an async block. Like an async fn body, it produces a future and runs nothing until it is polled.
Nothing runs until polled
This complete program makes the laziness visible. It reuses the block_on executor from the spine and adds a println! to the async body.
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut cx = Context::from_waker(&waker);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}
async fn greet(name: &str) -> String {
println!("running greet body");
format!("hello, {name}")
}
fn main() {
let fut = greet("Ada");
println!("future created");
let msg = block_on(fut);
println!("{msg}");
}The output is:
future created
running greet body
hello, Ada"running greet body" prints after "future created" because the body starts on the first poll, which happens inside block_on. If you dropped fut without polling it, the body would never run.
What .await does
.await can appear only inside an async context. It does not block the thread. Conceptually, fut.await does this:
- Poll the inner future with the current
Context. - If the result is
Ready(v), the.awaitexpression evaluates tovand the outer body continues. - If the result is
Pending, the outer future also returnsPendingto its caller and saves its position. - When it is polled again, it resumes at that same
.awaitand polls the inner future again.
Each .await is therefore a possible suspension point. The same Context, and so the same waker, is passed down through every level of nested awaits. When the innermost future is ready to make progress, it calls wake, and the executor polls the outermost future again.
You can write the same forwarding by hand. This wrapper doubles the value of an inner future. Add it to the previous program:
use std::pin::Pin;
struct Double<F>(F);
impl<F: Future<Output = u32> + Unpin> Future for Double<F> {
type Output = u32;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
match Pin::new(&mut self.0).poll(cx) {
Poll::Ready(v) => Poll::Ready(v * 2),
Poll::Pending => Poll::Pending,
}
}
}Calling block_on(Double(std::future::ready(21))) returns 42. The Pending arm is the same propagation an .await performs. The async version is:
async fn double(inner: impl Future<Output = u32>) -> u32 {
inner.await * 2
}The compiler generates the equivalent of Double. It also handles the case where inner is not Unpin, which is why pinning matters later in this tutorial.
Captured values and lifetimes
An async fn's future stores its arguments and any local variables that live across an .await. This has two consequences.
First, the future's type depends on what it captures. If an argument is a reference, the future cannot outlive the borrowed data. Compare greet(name: &str) above with the hand-written form, where the borrow must be named:
use std::future::Future;
fn len_of(s: &str) -> impl Future<Output = usize> + '_ {
async move { s.len() }
}An async fn adds this lifetime bound for you. A plain function returning impl Future may need + '_, depending on the edition.
Second, async move takes ownership of the variables it uses, while a plain async { ... } block borrows them. Use move when the future must outlive the scope that created it, for example when you return it or hand it to a spawned task.
fn make(n: u32) -> impl std::future::Future<Output = u32> {
// Without `move`, the block would borrow `n` from this stack frame.
async move { n + 1 }
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Warning: unused future | The call was not awaited or polled. | Add `.await`, or pass the future to an executor. |
| `await` is only allowed inside `async` functions and blocks | You used `.await` in a normal function. | Make the function `async`, or use an executor such as `block_on` at the boundary. |
| Borrowed value does not live long enough | An `async` block borrows a local and escapes its scope. | Use `async move`, or clone the data into the block. |
| Program hangs | The future returned `Pending` without registering a waker. | Make sure something calls `wake` when progress is possible. |
| Deadlock from nested executors | `block_on` was called inside async code, on a thread the runtime needs. | `.await` the future instead. |
Summary of the model
- An
async fnorasyncblock evaluates immediately to a future and runs no body code. - The future's
pollruns the body until the first.awaitthat returnsPending, then returnsPending. .awaitis a loop of poll-and-propagate, not a blocking wait.- The future stores whatever the body needs to resume, so its size and borrowing rules follow from its contents.
Exercise
In the program that defines greet, you change main to call let fut = greet("Ada"); and then never use fut again. What is printed, and why?
Show answer
Nothing is printed by greet. Calling greet only creates the future, and the body, including println!("running greet body"), runs only when the future is polled. Without block_on or an .await, no poll happens. The compiler also warns that the future is unused.
Exercise
Inside Double::poll, the inner future returns Poll::Pending. What must Double::poll return, and who is responsible for scheduling the next poll?
Show answer
It must return Poll::Pending. This forwarding is what .await does. The inner future is responsible for scheduling the next poll. It must call wake on the waker from cx, which Double passed down unchanged. The executor then polls Double again.