Expand description
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 theResultpassed to it, and will exit the current function by returning aTryFuturewhen it finds anErr. 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 anErrit will return a boxed future.
Please note: The
try_future!andtry_future_box!macros only accept inputs of typeResult. Alas, the equivalent ofasync/awaitis not yet possible in stable rust (however if you don’t shy away from using nightly, you could take a look at thefutures-awaitproject).
§Examples
§Using impl Future<_>
#[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<_>>
#[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 aBox<Future<_>>.
Structs§
- TryFuture
- Future which can either resolve immediately with a value or an error, or alternatively wrap another future performing some asynchronous task.