Running futures together in Rust
join! waits for several futures at once; try_join! gives up on the first error.
use tokio::time::{sleep, Duration};
async fn latency(ms: u64) -> u64 {
sleep(Duration::from_millis(ms)).await;
ms
}
async fn checked(ms: u64) -> Result<u64, String> {
if ms > 100 {
return Err(format!("{ms}ms is too slow"));
}
Ok(latency(ms).await)
}
#[tokio::main]
async fn main() {
let (a, b, c) = tokio::join!(latency(30), latency(10), latency(20));
println!("{a} {b} {c}");
let result = tokio::try_join!(checked(20), checked(500));
println!("{:?}", result);
}
How it works
join!polls every future concurrently on one task.- The results come back as a tuple, in order.
try_join!short-circuits when one returnsErr.
Keywords and builtins used here
ErrOkResultStringasyncawaitcheckedfniflatencyletmainreturnu64use
The run, in numbers
- Lines
- 22
- Characters to type
- 466
- Tokens
- 155
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 85 seconds.
Step 3 of 6 in Async with tokio, step 11 of 15 in Concurrency & async.