Rust’s async/await lets a computation wait for a result without blocking its thread, so other work can proceed. This is useful when a network request may take a while to return. section 19.3
An `async fn` returns a future: a value representing a result that may be ready later. For example, `async fn give_8() -> u8` returns a future whose output is `u8`, not an immediate `u8`. Calling the function creates the future; it must be polled to make progress. section 19.3.1 section 19.4
Use `.await` to wait for a future’s output. Polling means checking whether the future is ready: it returns `Poll::Pending` if it is not ready, or `Poll::Ready(value)` if it is. An async runtime manages these checks, so you normally do not call `poll` yourself. section 19.3.2 section 19.3.3
use tokio;
async fn async_give_8() -> u8 {
8
}
#[tokio::main] #1
async fn main() {
let some_number = async_give_8().await;
}
This small program uses Tokio to run an async main function, then awaits the future returned by `async_give_8` to obtain a `u8`. section 19.3.3
The compiler can help with two common first attempts. `.await` is allowed only inside an async function or block, but making a plain `main` async also produces an error. The `#[tokio::main]` attribute supplies a runtime: it turns the entry point into a regular `main` that runs the async body to completion. section 19.3.2 section 19.3.3
An async function can call regular functions, but those functions still block their thread while they run. A regular function that needs to await a future must itself use an async context. section 19.3.3
use reqwest;
use tokio;
#[tokio::main]
async fn main() {
let client = reqwest::Client::default();
let response = client
.get("https://www.rust-lang.org")
.send()
.await
.unwrap();
println!("{}", response.text().await.unwrap());
}
With reqwest’s default client, both sending the request and reading the response text are awaited. The example unwraps errors; real code should handle them. section 19.3.3
Awaiting several futures one after another waits for each before starting the next. Tokio’s `join!` instead polls multiple futures together. With three randomly delayed values, their completion messages can appear in different orders, while the result tuple remains `(1, 2, 3)`. section 19.3.4
use rand::*;
use tokio::join;
use std::time::Duration;
async fn wait_and_give_u8(num: u8) -> u8 {
let mut rng = rand::thread_rng();
let wait_time = rng.gen_range(1..100);
tokio::time::sleep(Duration::from_millis(wait_time)).await;
println!("Got a number! {num}");
num
}
#[tokio::main]
async fn main() {
let nums = join!(
wait_and_give_u8(1),
wait_and_give_u8(2),
wait_and_give_u8(3)
);
println!("{nums:?}");
}
The `join!` example starts three waits together and collects their results in a tuple. section 19.3.4
For other combinations, Tokio’s `select!` can take the first future to finish, while `try_join!` combines futures that return `Result` values and can report an error. section 19.3.4
















