Rust

Fan-Out with try_join_all

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Run N async operations concurrently and collect every Result. Fails fast on the first error; `join_all` is the variant that always waits for everyone.
Rust
Raw
// Cargo.toml: futures = "0.3"
use futures::future::try_join_all;
use std::time::Duration;
use tokio::time::sleep;

async fn fetch(id: u32) -> Result<String, String> {
    sleep(Duration::from_millis(50 * id as u64)).await;
    if id == 3 { return Err(format!("id {id} not found")); }
    Ok(format!("data-{id}"))
}

#[tokio::main]
async fn main() {
    let ids = vec![1, 2, 4, 5];               // no 3 → all succeed
    match try_join_all(ids.into_iter().map(fetch)).await {
        Ok(results) => println!("{results:#?}"),
        Err(e)      => eprintln!("at least one failed: {e}"),
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.