RRust By Example
advancedAsync

Async Basic

Introduction to async/await in Rust with futures.

Async Basic

Introduction to async/await in Rust with futures.

Difficulty

Advanced

Code

rust
use std::time::Duration;

async fn fetch_data(id: u32) -> String {
    // simulate async work
    tokio::time::sleep(Duration::from_millis(100)).await;
    format!("data for id {}", id)
}

#[tokio::main]
async fn main() {
    let result = fetch_data(42).await;
    println!("{}", result);

    // concurrent futures
    let (a, b) = tokio::join!(fetch_data(1), fetch_data(2));
    println!("{}, {}", a, b);
}

Explanation

async fn returns futures. .await suspends execution.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the async category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Async Examples