typestar

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

  1. async fn bodies are lazy — calling one does no work.
  2. .await yields control until that future is ready.
  3. #[tokio::main] wraps main in the runtime that drives them.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 6 in Async with tokio, step 9 of 15 in Concurrency & async.

← Previous Next →

async and await in other languages