Tokio Timeout With select!

Race an async operation against a timer using tokio select!, so a slow future is abandoned cleanly when the deadline fires first.

RustResilience

Code

snippet
use std::time::Duration;

use tokio::time::{sleep, timeout};

async fn fetch_remote() -> String {
    sleep(Duration::from_millis(200)).await;
    String::from("payload")
}

#[tokio::main]
async fn main() {
    match timeout(Duration::from_millis(50), fetch_remote()).await {
        Ok(body) => println!("received {body}"),
        Err(_) => println!("request timed out"),
    }

    tokio::select! {
        result = fetch_remote() => println!("first: {result}"),
        _ = sleep(Duration::from_millis(100)) => println!("deadline hit first"),
    }
}