0

Async Fn and Await Example in Rust

Last Updated on

This post provides examples that use async, async fn, and await for asynchronous processing. The codes use the futures crate to block the main function until the asynchronous function completes execution. Alternatively, we can use async-std.

Requirements

The following are used for this post

  • Windows 10
  • Rust 1.39.0
  • IntelliJ IDEA
  • Rust Plugin for IntelliJ
  • futures crate
    • This is to allow us to run async fn functions before the main function terminates
    • alternatively, async-std can be used for this post

Update Cargo.toml

Modify Cargo.toml as follows. Using futures is optional. Depending on your project, you might not need anything else for your asynchronous functions to work.

Async, Async Fn, and Await Codes

We put in some use statements.

Then, we create 2 examples of asynchronous functions that use async fn and await.

The second asynchronous function calls retrieval_val and uses the await keyword to resolve an expected value.

Async, Async Fn, and Await Demo

Then, we have our main function. It runs the pre_retrieval function.

We use block_on to allow pre_retrieval to complete its execution before the main function ends. When we run the codes, the output is something similar to this. In most cases, we don’t need the futures crate for codes that use async, async fn, and await.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer