Async & Await
Imagine you order a pizza. π Do you stand frozen at the counter staring at the oven the whole time? Probably not β you check your phone or chat with a friend while you wait, then grab your pizza when itβs ready. That smart way of waiting is exactly what async is all about.
Why waiting matters
Some jobs are fast, like adding two numbers. Other jobs are slow, like grabbing a picture from the internet. If your program just stood there during every slow job, it would feel sluggish and unresponsive. π΄
Async is the trick that says: βStart the slow thing, then go be useful somewhere else.β
Meet async and .await
In Rust we make a waiting-friendly function by writing async fn. And when we want to
wait politely for a slow result, we add .await after it.
async fnβ βthis function knows how to wait nicely.β.awaitβ βwait here for the answer, but let others work meanwhile.β
my_pizza.await β "let me know when my pizza is ready!"
Hereβs a little sketch of what async code looks like. (We wonβt run this one β keep reading to find out why!)
async fn make_toast() -> String {
String::from("crunchy toast π")
}
async fn breakfast() {
let toast = make_toast().await;
println!("Yum, {toast}");
}
A tiny helper: the runtime
Hereβs a secret: async code needs a helper to actually run it. That helper is called a
runtime. The most popular one in Rust is named tokio. Think of the runtime as a
busy waiter who keeps track of everyoneβs orders and brings each dish the moment itβs ready.
Since setting up a runtime is a more advanced step, letβs run a normal program that pretends to do its tasks in a smart order β the same idea async uses!
See how we did something useful in the middle of waiting? That βstay busy while waitingβ feeling is the heart of async. π
println!("Feed the cat π±"); β then press βΆ Run.
.await inside an async function. Using it in a
regular function will make Rust politely say "hey, this spot can't wait!"
Quick quiz
What does .await do?
Exactly! .await waits politely so your program can stay busy and useful. π
async fn knows how to wait, .await waits politely, and a
runtime like tokio actually runs it all. Next up, we'll
learn how to do many things at once with Tasks & Spawning! π