`.await`
.await suspends the current async function until a future is ready, then evaluates to that future's output. It may only appear inside async code.
Detailed Explanation
let body = response.text().await?; is three steps. text() returns a future. .await polls that future, yielding the worker if the bytes are not here yet. When the waker fires, the function resumes after .await with a Result<String, _>. ? then propagates the error. The order is await, then try: .await?, not ?.await.
.await is not thread::join. Other tasks on the same worker can run while this one is suspended. Your function's stackless state machine is stored in the task. Locals that are live across the .await must live in that state machine; that is why some types cannot cross an await (they are not Send and the task might move to another worker).
Cancellation happens at .await points. If the task is dropped, it resumes nowhere; the future being awaited is dropped. Code between await points runs to the next await without being cancelled. Keep critical sections short and do not assume that a function that has started will finish if its caller used timeout or select!.
You cannot write .await in a sync function, in a Drop impl, or in an ordinary Iterator method. Those contexts have no executor. block_on is the escape hatch and is not something to call from inside a running runtime (nested runtimes panic or stall).
When you write .await: every I/O future, every spawned join, every sleep. When you forget it: the future is created and, if unused, dropped — a silent cancel. The compiler's must_use on many futures is there to catch that.
Code Examples
async fn double_after(n: i32) -> i32 {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
n * 2
}
#[tokio::main]
async fn main() {
println!("{}", double_after(21).await); // prints: 42
}Common Gotchas
`.await` is only valid in `async`
A sync helper cannot await. Make it async, or take the already-resolved value.
Cancellation is at await points
`timeout(fut)` drops `fut` at its current await. Use a cancellation-safe pattern for writes that must complete.
Write `.await?` not `?.await`
`?` applies to the output of the future, so the future must finish first.
Holding a std `MutexGuard` across `.await` can deadlock a worker
Drop the guard, or use an async mutex.