Function async_ui_web::race

source ·
pub fn race<F>(f: F) -> <F as Race>::Futurewhere
    F: Race,
Expand description

Wait for the first future to complete.

Race takes in many “subfutures” and return a single Future. When awaited, the returned Future will drive all of the subfuture until any of them complete, and return the result of that completed subfuture.

Subfutures may be passed in as either

  • a tuple of up to 12 Futures, all with the same output type (signature: (F1, F2, F3, ...) -> Output)
  • an array of Futures (signature: [F; N] -> F::Output)
  • a Vec of Futures (signature: Vec<F> -> F::Output)
async fn do_something(input: i32) -> i32 {
    // ...make a network request of something...
    input * 2
}
// Race 2-tuple of Futures
let result = race((
    do_something(21),
    do_something(100)
)).await;
// Don't know which one will win the race.
assert!(result == 42 || result == 200);

// Race array of Futures
let result: i32 = race(
    core::array::from_fn::<_, 10, _>(|idx| do_something(idx as i32))
).await;

// Race vector of Futures
let result: i32 = race(
    (0..100).map(|i| do_something(i as i32)).collect::<Vec<_>>()
).await;