Rust: Future, Async, Await (A Summary)

Pai Lee Wai
2 min readApr 22, 2019

--

Photo by Kimberly Farmer on Unsplash

*Updates for new async/await is in progress.

Recently, I was dealing with asynchronous future for hyper.rs while developing a web development framework (Obsidian). After I did some research into it, I wanted to conclude what I have learned for it.

*This article used Rust 1.33.0 Nightly as the Rust toolchain.

Future Crate

According to Rust future crate docs, futures are a concept for an object which is a proxy for another value that may not be ready yet. Meaning that the implementation of that future object may be done in somewhere future.

Simple Success Future
Simple Error Future

After process instructions can be chained by using .then() and .and_then().

Future Chaining

The main process can enter the other instructions while the future process is running provided both processes is not run on the same thread. If the same thread is used, the future will only be run when it is needed (thread is free to use).

Future Block in Single Thread

If there is variable need to be used in the chain closure, the non-static captured value usually is needed to be moved. This is because there is the chance of the chain closure will only be processed after the captured value lifetime end.

Future Closure Captures

Normally, executor such as Tokio executor will be used to run futures. By using Tokio executor and spawn, asynchronous runtime non-blocking behavior can be achieved.

Tokio Default Executor

Result:

Tokio Executor Output

Async/Await

Async/Await is a popular approach to write asynchronous code in languages such as C#, Python and JavaScript. The reason for its high popularity is it allowed developers to write asynchronous code in synchronous code design.

In Rust community, this approach is also proposed in Rust 2018 Networking Working Group and the development is ongoing right now. Currently, we can only use the function in Nightly Rust.

Async/Await example

In this example, we can read and trace the code from top to down easily since it is in top-down order. Unlike previous future crate approach, the flow is not in order and that worsens the readability of the code. Of course, concurrent processing can be done as well by using Tokio “spawn_async” function.

Tokio Spawn Async

Recently, Async Working Group announced a new crate Runtime. This crate is pretty cool as it simplified the executor and spawn. This makes the code is even more readable!

Some Reference Recommendation

--

--