Of course! This is a very common requirement when moving from JavaScript/Node.js to Rust's async ecosystem.
In JavaScript, Promise.all(iterable) takes an array of promises and returns a single promise that fulfills when all of the input promises have fulfilled.
In Rust, you have a couple of excellent options depending on your specific use case. The most common ones are the join! macro and the join_all function.
1. For a Fixed Number of Futures: tokio::join!
When you know exactly which futures you want to run at compile time, the join! macro (from either tokio or the futures crate) is the most idiomatic and efficient choice. It runs the futures concurrently and returns a tuple of their results.
Key Idea: It's like Promise.all but for a fixed set of tasks.
use tokio::time::{sleep, Duration};
// A function that simulates a network call
async fn fetch_data_from_service_a() -> String {
println!("Service A: Fetching data...");
sleep(Duration::from_millis(1000)).await;
println!("Service A: Done.");
"Data from A".to_string()
}
// Another function that simulates a different network call
async fn fetch_data_from_service_b() -> String {
println!("Service B: Fetching data...");
sleep(Duration::from_millis(1500)).await;
println!("Service B: Done.");
"Data from B".to_string()
}
#[tokio::main]
async fn main() {
let start = std::time::Instant::now();
// Create the futures, but don't .await them yet.
let future_a = fetch_data_from_service_a();
let future_b = fetch_data_from_service_b();
// Use join! to run both futures concurrently.
// It will wait until both are complete.
let (result_a, result_b) = tokio::join!(future_a, future_b);
println!("\n--- Results ---");
println!("Result from A: {}", result_a);
println!("Result from B: {}", result_b);
println!("Total time elapsed: {:.2?}", start.elapsed());
// Note: The total time will be ~1.5s, not 1.0s + 1.5s = 2.5s
}
Cargo.toml dependencies:
[dependencies]
tokio = { version = "1", features = ["full"] }
2. For a Dynamic Number of Futures: futures::future::join_all
When you have a list or vector of futures (e.g., from a loop), you can't use join! because the number isn't fixed at compile time. In this case, you should use the join_all function from the futures crate.
Key Idea: This is the direct equivalent of Promise.all for a dynamic array.
use futures::future::join_all;
use tokio::time::{sleep, Duration};
async fn fetch_user_data(id: u32) -> String {
println!("Fetching data for user {}...", id);
// Simulate varying network latency
sleep(Duration::from_millis(800 + (id as u64 * 100))).await;
format!("User data for {}", id)
}
#[tokio::main]
async fn main() {
let start = std::time::Instant::now();
let user_ids = vec![1, 2, 3, 4, 5];
// Create a vector of futures without awaiting them
let futures = user_ids.into_iter()
.map(fetch_user_data)
.collect::<Vec<_>>();
// Await all futures concurrently.
// join_all returns a Vec containing the result of each future.
let results = join_all(futures).await;
println!("\n--- All futures completed ---");
for (i, result) in results.iter().enumerate() {
println!("Result for ID {}: '{}'", i + 1, result);
}
println!("Total time elapsed: {:.2?}", start.elapsed());
}
Cargo.toml dependencies:
[dependencies]
tokio = { version = "1", features = ["full"] }
futures = "0.3"
Important: Error Handling (The "Fail-Fast" Behavior)
There's a crucial difference between Promise.all and the Rust functions above.
Promise.all: Fails fast. If any single promise rejects, the entire Promise.all immediately rejects with the reason of the first one that failed.
join! and join_all: Do not fail fast. They wait for all futures to complete, even if some of them result in an Err. This is actually closer to JavaScript's Promise.allSettled.
How to get the "fail-fast" behavior of Promise.all?
Use try_join! and futures::future::try_join_all. These variants work on futures that return a Result<T, E>. If any future returns an Err, the whole operation immediately returns that Err and cancels the other futures.
Example with try_join!
use std::io;
// This operation might fail
async fn successful_task() -> Result<String, io::Error> {
Ok("Success!".to_string())
}
// This one will fail
async fn failing_task() -> Result<String, io::Error> {
Err(io::Error::new(io::ErrorKind::Other, "Something went wrong"))
}
#[tokio::main]
async fn main() {
// try_join! will short-circuit and return the first Err
let result = tokio::try_join!(successful_task(), failing_task());
match result {
Ok((res_a, res_b)) => {
// This arm will not be reached
println!("Both succeeded: {} and {}", res_a, res_b);
}
Err(e) => {
println!("An operation failed: {}", e);
}
}
}
Summary Table
| JavaScript Equivalent | Rust Equivalent | Use Case | Behavior on Error |
|---|
Promise.all(promises) | try_join!(...) or try_join_all(...) | When you want to fail immediately if any task fails. | Fail-fast. Returns the first Err. |
Promise.allSettled(promises) | join!(...) or join_all(...) | When you want all tasks to complete, regardless of success or failure, and then inspect their individual outcomes. | Completes all. You get a collection of Results to inspect. |
| - | join! / try_join! | A fixed, known number of futures. | - |
| - | join_all / try_join_all | A dynamic Vec or iterator of futures. | - |