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.
1 2 3 4 5 6 7 8 | [package] name = "async-fn" version = "0.1.0" authors = ["ksangabriel"] edition = "2018" [dependencies] futures = "0.3.1" |
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.
1 2 3 4 | use std::time::Duration; use futures::executor::block_on; use std::thread::sleep; ... |
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.
1 2 3 4 5 6 7 8 | async fn retrieve_val() -> i32 { // Simulates some delays, e.g., network latency let ten_secs = Duration::from_secs(10); sleep(ten_secs); // return some value 5 } |
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.
1 2 3 4 | async fn pre_retrieval() { let o = retrieve_val().await; println!("{:?}", o); } |
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.
1 2 3 4 | fn main() { let o = pre_retrieval(); block_on(o); } |
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.
1 2 3 4 5 6 7 | C:/Users/xxxx/.cargo/bin/cargo.exe run --color=always --package async-fn --bin async-fn Compiling async-fn v0.1.0 (C:\Users\xxxx\Desktop\ccc\_m\rust\async-fn) Finished dev [unoptimized + debuginfo] target(s) in 2.49s Running `target\debug\async-fn.exe` 5 Process finished with exit code 0 |
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.