In Rust, what does .await actually do with a future, and how does a Poll::Pending from deep inside reach the executor?
answer
- one trait, one method
- Ready(value) or Pending
- the Context travels down
- Pending bubbles up, wake re-polls
basics
~20 s.await calls IntoFuture::into_future, then polls the future with the current task's Context. If it returns Poll::Pending, the enclosing async body returns Pending too, the chain unwinds to the executor, and the task is polled again after its Waker fires.
solid answer
~40 s`Future` has one method, `poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>`, returning `Poll::Ready(value)` or `Poll::Pending`. An `.await` converts its operand with `IntoFuture::into_future`, pins it, and polls it, passing down the same `Context` its own caller supplied. On `Ready(v)`, `v` becomes the value of the expression. On `Pending`, the enclosing async body saves its place and returns `Pending` to whoever polled it, and so on up to the executor, which polled the outermost future. The async bodies in between never touch the `Waker`; the leaf future that is genuinely waiting, a socket or a timer, stores it from `cx`; when it calls `wake`, the executor polls the top-level future again, which resumes at the suspended `.await` and polls the leaf once more. No thread blocks anywhere.
code
rust · 33 linesuse std::future::Future;
use std::pin::{Pin, pin};
use std::task::{Context, Poll, Waker};
struct YieldOnce { yielded: bool }
impl Future for YieldOnce {
type Output = u32;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
if self.yielded {
return Poll::Ready(42);
}
self.yielded = true;
cx.waker().wake_by_ref(); // ask to be polled again
Poll::Pending
}
}
fn main() {
let mut task = pin!(async {
println!("before await");
let v = YieldOnce { yielded: false }.await;
println!("after await: {v}");
v + 1
});
let mut cx = Context::from_waker(Waker::noop());
for i in 1.. {
match task.as_mut().poll(&mut cx) {
Poll::Pending => println!("poll {i}: Pending"),
Poll::Ready(v) => { println!("poll {i}: Ready({v})"); break; }
}
}
}go deeper
Know that Future has one method, poll, and that it returns Poll::Ready with a value or Poll::Pending. Say that .await never blocks a thread.
Walk through the Reference's steps for .await, explain that the same Context is passed down the chain, and that only leaf futures use the Waker.
Explain the wake guarantee, coalesced wakes, and why re-polling starts from the top of the task; connect a missing wake to a task that hangs forever.
Relate the poll protocol to runtime independence: any executor that builds a Context from its own Waker can drive any library's futures.
## The trait in one method The whole asynchronous model in Rust rests on one trait in `core::future`: ```rust pub trait Future { type Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>; } ``` - **`Output`** is the type the computation eventually produces. - **`poll`** *attempts* to finish the computation. It should not block: the docs ask an implementation to return quickly and to offload long work elsewhere. - **`Poll<T>`** is a plain enum with two variants: `Poll::Ready(T)` when the value is available, and `Poll::Pending` when it is not yet. - **`Context<'_>`** is the task context; today its useful content is `cx.waker()`, a `&Waker` that can wake the task this poll belongs to. - **`self: Pin<&mut Self>`** promises the future will not move between polls; why that matters is the subject of the lesson on `Pin` and `Unpin`. A **task** is the top-level future an executor owns. Everything awaited inside it is polled as part of that one task, with that task's `Context`. ## What a single `.await` does The Reference spells out the effect of `operand.await`: 1. Call `IntoFuture::into_future` on the operand, which for an ordinary future returns the future itself. 2. Pin the resulting future in place. 3. Call `Future::poll` on it, passing the current task context. 4. If `poll` returns `Poll::Pending`, the enclosing async context returns `Poll::Pending` too, saving its state so that the next poll of the enclosing future resumes at step 3. 5. If it returns `Poll::Ready(v)`, `v` is the value of the `.await` expression and execution continues. So `.await` is a **poll loop that yields instead of spinning**: each round is one call to `poll`, and between rounds control leaves the function entirely. ## How `Pending` travels up and the wake travels down Picture `handle_request` awaiting `read_frame`, which awaits a socket read: | Layer | What its `poll` does | |---|---| | executor | polls the task's top-level future with a `Context` built from that task's `Waker` | | `handle_request` (async fn) | resumes at its current `.await`, polls `read_frame` with the same `cx` | | `read_frame` (async fn) | resumes at its `.await`, polls the socket future with the same `cx` | | socket future (leaf) | data not there: clones `cx.waker()`, registers it with the I/O source, returns `Pending` | `Pending` then returns through `read_frame` and `handle_request` to the executor, which parks the task. Later the I/O source calls `wake()` on the stored `Waker`. The `wake` docs guarantee that, while the executor keeps running and the task is unfinished, each wake is followed by at least one later poll of that task, and several wakes may be coalesced into one poll. That poll starts again at the top: the executor polls `handle_request`, which jumps straight to its suspended `.await` and polls `read_frame`, which polls the socket future, which now returns `Ready`. Two consequences follow: - **Async fns never touch the `Waker` themselves.** They forward `cx`. Registering a waker is the job of leaf futures, hand-written ones that actually wait on something; some library combinators also wrap the waker to learn which child woke, which the material on concurrent futures covers. - **Nothing blocks a thread.** A `Pending` is an ordinary return value; the executor's thread is free to poll other tasks. ## Watching it happen The runnable example polls an async block by hand with `Waker::noop()` (stable since 1.85), a waker that does nothing, and a manual loop standing in for an executor. The inner `YieldOnce` future returns `Pending` once, after calling `wake_by_ref`, and the output shows the async block returning `Pending` on poll 1 and `Ready(43)` on poll 2. The line after the `.await` prints only on the second poll, because the first poll returned from the middle of the block. ## What `.await` is not - It is not a blocking wait: blocking belongs to `std::thread::sleep` or a synchronous read, and calling those inside an async fn stalls the executor thread, which the lesson on runtimes and blocking covers. - It does not start concurrent work: two `.await`s in a row run one after the other. Running futures concurrently on one task is what `join!` does, covered with concurrent futures. - It is not tied to one runtime: the same `poll` and `Context` protocol is what every executor speaks. - It is not free of state: whatever is alive across an `.await` must be kept somewhere between polls, inside the future itself, which is why the lessons on async functions and on `Send` futures care about what an `.await` holds.
- If an async fn awaits three futures in sequence and each returns Pending once, how often is the task's top-level future polled?At least four times: one poll that reaches the first Pending, then one more after each wake, each poll resuming at the suspended .await. Executors may coalesce wakes, but a Pending never makes progress without a later poll.
- Does the executor call poll on the innermost future directly after a wake?No. It polls the task's top-level future; the compiler-generated code resumes at its suspended .await and polls the inner future, and so on down to the leaf. The Waker identifies the task, not one future inside it.
- Why does poll take a Context rather than a Waker directly?Context is a wrapper that today exposes cx.waker() and leaves room to carry more task data later without changing the trait signature. A leaf future reaches the Waker through it with cx.waker().
- .await blocks the current thread until the inner future is ready.
- Every async fn must clone the Waker and store it before each .await.
- Poll::Pending means the operation failed and must be retried with a new future.
- After a wake, the executor polls only the innermost future that returned Pending.
- An executor should keep calling poll in a tight loop until Ready comes back.