async and await in Rust
An async fn returns a future: nothing runs until a runtime polls it.
use tokio::time::{sleep, Duration};
async fn fetch(name: &str) -> String {
sleep(Duration::from_millis(50)).await;
format!("{name} loaded")
}
#[tokio::main]
async fn main() {
let first = fetch("basics").await;
println!("{first}");
let second = fetch("traits");
println!("not started yet");
println!("{}", second.await);
}
How it works
async fnbodies are lazy — calling one does no work..awaityields control until that future is ready.#[tokio::main]wraps main in the runtime that drives them.
Keywords and builtins used here
Stringasyncawaitfetchfnletmainstruse
The run, in numbers
- Lines
- 16
- Characters to type
- 324
- Tokens
- 100
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 55 seconds.
Step 1 of 6 in Async with tokio, step 9 of 15 in Concurrency & async.