Rust, Software Development

Async Fn and Await Example in Rust That’ll Open Your Mind

Rust lang

This post shows code examples that use async, async fn, and await for asynchronous processing. For demonstration purposes, our codes use the futures crate just to block the main function until the asynchronous function completes execution. Alternatively, we can use async-std.

What We Used For This Post – Aka Requirements

We used the following stuff for this post.

  • Windows 10
  • Rust 1.39.0
  • IntelliJ IDEA
  • Rust Plugin for IntelliJ
  • futures crate
    • This crate will allow us to block the main function and let the async fn functions complete their executions
    • alternatively, we can use async-std for this post, but we need to change some codes a little bit

Create A Rust Project And Update Cargo.toml

First, we need to create a Rust project. Then, 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

Next, we replace the content of the main.rs file with our codes. We start with the use statements as follows.

Then, we create two examples of asynchronous functions that use async fn and await. The first function is retrieve_val, whose purpose is to return the value numeric value five after ten seconds.

The other asynchronous function is pre_retrieval, which calls the retrieval_val function. The pre_retrieval uses the await keyword to resolve an expected value – it will wait asynchronously.

Async, Async Fn, and Await Demo

At this point, we have prepared the asynchronous functions to test. Next, we code our main function to call the pre_retrieval function. Please note that we are blocking the main function until the pre_retrieval function completes its execution.

We use block_on to allow pre_retrieval to finish its operation before the main function ends. When we run the codes, we get the following output.

In most cases, we do not need the futures crate for codes to work with async, async fn, and await.

This post is now part of Rust Programming Language For Beginners Tutorial.

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *