Skip to content

Add Future::timeout() method #6047

@petrzjunior

Description

@petrzjunior

Is your feature request related to a problem? Please describe.
Currently, the code to timeout a Future is

let _ = timeout(Duration::from_secs(3), listener.accept())
    .await
    .expect("timeout")
    .expect("accept failed");

I propose it should be possible to write

let _ = listener.accept()
    .timeout(Duration::from_secs(3))
    .await
    .expect("timeout")
    .expect("accept failed");

This results in cleaner code following the fluent style of writing.

Describe the solution you'd like
I propose adding a Future extension method

fn timeout(self, timeout: Duration) -> Timeout<Self>

Describe alternatives you've considered
The current method timeout(Duration, Future) works, but is less readable.

Additional context
The proposed method used to be in Tokio in the past:

fn timeout(self, timeout: Duration) -> Timeout<Self>
where
Self: Sized,
{
Timeout::new(self, timeout)
}

It got removed in #1774 refactoring.

Similar method is implemented in async_std since 2019 async-rs/async-std#600.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-tokioArea: The main tokio crateC-feature-requestCategory: A feature request.M-timeModule: tokio/time

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions