Crate try_future[][src]

This crate aims to provide a convenient short-hand for returning early from futures-based functions.

The general pattern it supports is where before a function performs an asynchronous task, it does some work that might result in an early termination, for example:

  • certain parsing or validation logic that might fail, and upon which the function should return immediately with an error
  • some local cache lookup or other optimization that might render the asynchronous task unnecessary, and where the function should instead return immediately with a value

To that end, the TryFuture struct implements a future which can either resolve immediately with a value or an error, or alternatively wrap another future performing some asynchronous task.

The equivalent of try! or the ? operator is provided by the try_future! and try_future_box! macros:

  • try_future! will inspect the Result passed to it, and will exit the current function by returning a TryFuture when it finds an Err. Otherwise it will unwrap the result and pass back the value inside the result.

  • try_future_box! works in the same way, except that when encountering an Err it will return a boxed future.

Please note: The try_future! and try_future_box! macros only accept inputs of type Result. Alas, the equivalent of async/await is not yet possible in stable rust (however if you don't shy away from using nightly, you could take a look at the futures-await project).

Examples

Using impl Future<_>

This example is not tested
#[macro_use] extern crate try_future;

fn make_request<C: Connect>(target: &str, client: &Client<C>) ->
    impl Future<Item=Response, Error=Error>
{
    let uri = try_future!(target.parse::<Uri>());

    client.get(uri).into()
}

Using Box<Future<_>>

This example is not tested
#[macro_use] extern crate try_future;

fn make_request<C: Connect>(target: &str, client: &Client<C>) ->
    Box<Future<Item=Response, Error=Error>>
{
    let uri = try_future_box!(target.parse::<Uri>());

    Box::new(client.get(uri))
}

Macros

try_future

Equivalent of try! returning a [TryFuture`](TryFuture).

try_future_box

Equivalent of try! returning a Box<Future<_>>.

Structs

TryFuture

Future which can either resolve immediately with a value or an error, or alternatively wrap another future performing some asynchronous task.