pub async fn timeout<F, T, E>(
duration: Duration,
future: F,
) -> Result<T, TimeoutError<E>>
Available on crate feature
async
only.Expand description
Applies a maximum duration to a Result
-returning future.
Whether the maximum duration was reached is indicated via the error type. Specifically:
- If
future
does not complete withinduration
, returnsTimeoutError::DeadlineElapsed
. - If
future
completes withOk(t)
, returnsOk(t)
. - If
future
completes withErr(e)
, returnsTimeoutError::Inner(e)
.
Using this function can be considerably more readable than
tokio::time::timeout
when the inner future returns a Result
.
§Examples
use mz_ore::future::TimeoutError;
let slow_op = async {
tokio::time::sleep(Duration::from_secs(1)).await;
Ok::<_, String>(())
};
let res = mz_ore::future::timeout(Duration::from_millis(1), slow_op).await;
assert_eq!(res, Err(TimeoutError::DeadlineElapsed));