Skip to main content

with_timeout

Function with_timeout 

Source
pub async fn with_timeout<F, T, E>(
    duration: Duration,
    context: impl Into<String>,
    future: F,
) -> Result<T, TimeoutError<E>>
where F: Future<Output = Result<T, E>>,
Expand description

Execute a future with a timeout.

§Arguments

  • duration - Maximum time to wait for the future to complete.
  • context - Description of the operation for error messages.
  • future - The async operation to execute.

§Returns

Returns Ok(T) if the future completes within the timeout, Err(TimeoutError::Timeout) if the timeout expires, or Err(TimeoutError::ExecutionError) if the future returns an error.

§Examples

use std::time::Duration;
use thulp_skills::timeout::with_timeout;

async fn example() {
    let result = with_timeout(
        Duration::from_secs(5),
        "fetch data",
        async { Ok::<_, std::io::Error>("data") }
    ).await;
     
    assert!(result.is_ok());
}