Awaiting the future

In the last section, we saw how tasks composed of multiple futures are often difficult to write and debug. One attempt at remedying this is using a crate that wraps futures and associated error handling, yielding a more linear flow of code. This crate is called futures-await and is under active development.

This crate provides two primary mechanisms of dealing with futures:

  • The #[async] attribute that can be applied to functions, marking them as asynchronous. These functions must return the Result of their computation as a future.
  • The await! macro that can be used with async functions to consume the future, returning a Result.

Given these constructions, our earlier example download will look like this:

#[async]fn download(url: ...

Get Network Programming with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.