1. What Is Asynchronous Programming?
Asynchronous programming allows a program to start an operation and make progress on other work while waiting for that operation to complete.
Consider a simple example.
Suppose your application needs to:
- Fetch student information from an API.
- Fetch fee information from a database.
- Send a notification.
With synchronous programming, these operations may happen one after another.
With asynchronous programming, independent operations can make progress concurrently.
Synchronous Example
Asynchronous Programming
Async programming allows tasks to pause when waiting and resume when their required result becomes available.
This is particularly useful for operations involving network requests, databases, and file I/O.
2. Understanding async
The async keyword is used to define an asynchronous function or block.
Example:
However, there is something important to understand.
Calling an async function does not immediately execute its body.
Instead, it creates a value called a Future.
For example:
Output:
Notice that Hello Rust is not printed.
Why?
Because the Future has not been executed by an asynchronous runtime or otherwise polled.
3. What Is a Future?
A Future represents a value that may become available later.
You can think of it as a task that has not finished yet.
For example:
- A web request waiting for a response.
- A database query waiting for results.
- A file operation waiting to complete.
Rust provides the Future trait.
A simplified definition looks like this:
You do not normally need to implement this trait manually when starting with async Rust.
Rust generates Future implementations for async functions.
4. What Is an Async Runtime?
Rust's standard library provides the Future abstraction, but it does not include a built-in asynchronous runtime.
A runtime executes and schedules asynchronous tasks.
Popular Rust asynchronous runtimes include:
- Tokio
- async-std
In this course, we will use Tokio because it is widely used for network applications and backend development.
Installing Tokio
Open your Rust project folder.
Run:
This adds Tokio to your Cargo.toml.
Alternatively, add it manually:
The full feature enables a broad set of Tokio features, including its runtime, timers, synchronization tools, and networking support.
5. Your First Async Program Using Tokio
Create or update src/main.rs.
Run:
Output:
Explanation:
async fn main()defines an asynchronous main function.#[tokio::main]creates a Tokio runtime.- Tokio executes the async main function.
The Rust compiler does not allow an ordinary async fn main() as the executable entry point without a runtime or another mechanism to execute it.
6. Understanding await
The await keyword waits for an asynchronous operation to produce its result.
Example:
Output:
Explanation:
get_student()creates a Future..awaitwaits for the Future to complete.- The resulting String is assigned to
student.
Important: .await can only be used inside an async context.
7. Understanding tokio::time::sleep()
Tokio provides an asynchronous sleep function.
Example:
Output:
The second message appears after approximately two seconds.
Notice the difference between:
and:
Thread sleep | Async sleep |
|---|---|
Blocks the current thread | Suspends the current async task |
Uses | Uses |
Other tasks on that thread cannot run | Runtime can execute other tasks |
8. Understanding tokio::spawn()
Tokio provides tokio::spawn() to create a new asynchronous task.
Example:
Possible Output:
Explanation:
tokio::spawn()creates a new asynchronous task.handlestores the JoinHandle..awaitwaits for that task to finish.unwrap()handles a possible task failure.
A spawned Tokio task generally must satisfy the Send + 'static requirements. This is why moving owned values into spawned tasks is common.
9. Running Multiple Async Tasks Concurrently
One of the biggest benefits of asynchronous programming is that multiple tasks can make progress concurrently.
Example:
Possible Output:
Both tasks wait for approximately two seconds concurrently rather than waiting four seconds sequentially.
The exact output order can vary.
10. Understanding tokio::join!
You can use tokio::join! to run multiple Futures concurrently and wait for all of them.
Example:
Output:
Both operations take approximately two seconds of waiting time rather than four seconds when awaited sequentially.
Difference Between join! and spawn()
|
|
|---|---|
Runs Futures concurrently in the current task | Creates a separate Tokio task |
Returns results together | Returns JoinHandles |
Does not require spawning separate tasks | Spawned tasks have |
Useful for coordinating several operations | Useful for independently scheduled tasks |
11. Understanding tokio::try_join!
Sometimes multiple operations can fail.
Tokio provides try_join! to wait for multiple Results.
If one Future returns an error, the macro returns that error and drops the remaining Futures.
Example:
Output:
Here, both functions return Result, so try_join! can propagate an error.
12. Understanding Async Functions with Parameters
Async functions can accept parameters just like regular functions.
Example:
Output:
You can also use async functions with multiple parameters.
13. Async Programming with Error Handling
Async functions can return Result<T, E> just like normal functions.
Example:
Output:
Using the ? Operator
You can also use ? with asynchronous operations.
The ? operator propagates the error from get_student() to show_student().
14. Async Programming with HTTP Requests
One of the most common uses of async Rust is making HTTP requests.
For this example, we will use the reqwest library.
Step 1: Install Dependencies
Run:
Step 2: Create the Program
Example Output:
The exact title is supplied by the API and may change.
Explanation
reqwest::get()sends an HTTP GET request..awaitwaits for the response.response.json()converts the response body into thePoststructure.Deserializeallows Serde to deserialize JSON into Rust data.?propagates possible errors.
This is similar to calling an API from a Laravel backend application.
15. Understanding Async vs Multithreading
Both asynchronous programming and multithreading can help applications handle multiple tasks.
However, they work differently.
Async Programming | Multithreading |
|---|---|
Uses Futures and an async runtime | Uses operating-system threads |
Tasks can pause while waiting | Threads execute independently |
Excellent for I/O-bound operations | Useful for parallel CPU-intensive work |
Tasks are generally lightweight | Threads usually have greater resource overhead |
Uses | Uses |
Important: Async programming does not automatically mean that code runs on multiple CPU cores.
An asynchronous runtime can execute many tasks on one thread or across multiple threads.
16. Understanding Blocking Operations
A blocking operation prevents the current thread from doing other work while it waits.
Example:
Using this directly inside an async task can block a Tokio worker thread.
Prefer:
For blocking operations that cannot be made asynchronous, Tokio provides spawn_blocking().
Example:
This moves the blocking or CPU-intensive closure to Tokio's blocking thread pool.
17. Common Mistakes
Mistake | Explanation |
|---|---|
Calling an async function without awaiting or spawning it | The Future is created but not executed |
Using |
|
Forgetting to configure a runtime | Async code needs an executor to be polled |
Using blocking sleep in an async task | It blocks the runtime worker thread |
Confusing concurrency with parallelism | Concurrent tasks do not necessarily execute simultaneously |
Forgetting error handling | Async operations can also fail |
Using borrowed local data in | Spawned tasks generally require |
18. Practice Exercises
Exercise 1:
Create an async function called hello().
Display:
Call it from a Tokio main function.
Exercise 2:
Create an async function called get_name() that returns a String.
Use .await to get the result.
Exercise 3:
Create two async functions:
get_student()get_course()
Use tokio::join! to execute them concurrently.
Exercise 4:
Create an async function that returns:
Use match to handle the result.
Exercise 5:
Make an HTTP GET request using reqwest and display the response status.
19. Mini Project: Async Student Information System
Create a small application that retrieves student and course information asynchronously.
Requirements
- Create an async function named
get_student(). - Create an async function named
get_course(). - Make both functions wait for one second.
- Use
tokio::join!to execute them concurrently. - Display both results.
Complete Code
Expected Output
Both asynchronous operations take approximately one second of waiting time when run concurrently.