How to Use tokio

:spawn for Spawning Async Tasks

Use tokio::spawn to run async code in the background and get a handle to retrieve the result later.

Use tokio::spawn to run an async function in the background without blocking the current task. Pass the async function call (without .await) to spawn, which returns a JoinHandle you can use to wait for the result later.

use tokio::task::JoinHandle;

#[tokio::main]
async fn main() {
    let handle: JoinHandle<String> = tokio::spawn(async {
        "Hello from spawned task!".to_string()
    });

    let result = handle.await.unwrap();
    println!("Result: {result}");
}