Futures

Juggling with mio's socket polling state machine is not very convenient. To provide a higher-level API that can be used by application developers, we have the futures crate. The futures crate provides a trait named Future, which is the core component of the crate. A future represents the idea of a computation that is not immediately available, but might be available later. Let's look at its type signature of the Future trait to get more information about it:

pub trait Future {
type Item;
type Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error>;
}

A Future is an associated type trait that defines two types: an Item type representing the value that the Future will resolve to and an Error type that specifies what error type the future will fail with. They are quite similar to the Result type in the standard library, but instead of getting the result right away, they don't compute the immediately.

A Future value on its own cannot be used to build asynchronous applications. You need some kind of reactor and an event loop to progress the future toward completion. By design, the only way to have them succeed with a value or fail with an error is to poll them. This operation is represented by the single require method known as poll. The method poll specifies what should be done to progress the future. A future can be composed of several things, chained one after another. To progress a future, we need a reactor and an event loop implementation, and that is provided by the tokio crate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset