# Futures and the Async Syntax
The key parts of asynchronous programming in Rust are _futures_ and Rust's `async` and `await` keywords
A _future_ or a promise is a value that may not be ready now but will become ready at some point in the future
In other languages the same concept shows up under other names such as _task_ or _promise_.
Rust provides a `Future` trait as a building block so that different async operations can be implemented with different data structures but with a common interface.
Rust futures are types that implement the `Future` trait.
Each future holds its own information about the progress that has been made and what "ready" means.
You can apply the `async` keyword to blocks and functions to specify that they can be interrupted and resumed.
Within an async block or async function, you can use the `await` keyword to _await a future_ (that is, wait for it to become ready).
Any point where you await a future within an async or function is a potential spot for that async block or function to pause and resume.
The process of checking with a future to see if its value is available yet is called _polling_.
Some other languages, such as C# and JavaScript, that also use `async` and `await` keywords for async programming.
There are some significant differences in how Rust does things, including how it handles the syntax.
When writing async Rust, we use the `async` and `await` keywords most of the time.
Rust compiles them into equivalent code using the `Future` trait, much as it compiles `for` loops into equivalent code using the `Iterator` trait.
Due to Rust providing the `Future` trait, this means that you can also implement it for your own data types you need to.
Many of the functions that we will see have return types with their own implementations of `Future`.
We will return to the definition of the trait at the end of the chapter and dig into more of how it works.
This may all feel a bit abstract so we will go into our first program: a little web scraper.
We will pass in two URLs form the command line, fetch both of them concurrently and return the result of whichever one finishes first.
This will have a fair bit of new syntax.
## Our First Async Program
To keep focus on learning async rather than juggling parts of the ecosystem, we created the `trpl` crate (this is sort for "The Rust Programming Language").
This re-exports all the types, traits, and functions you will need, primarily form the [`futures`](https://crates.io/crates/futures) and [`tokio`](https://tokio.rs/) crates.
The `futures` crate is an official home for Rust experimentation for async code, and it is where the `Future` trait was orignially designed.
Tokio is the most widely used `async` runtime in Rust today, especially for web applications.
Here we the `tokio` crate under the hood for `trpl` becuase it is well tested and widly used.
In some cases `trpl` also renames or wraps the original APIs to keep us focused on the details relevant to this chapter.
If you want to understand in depth of what the crate does, check out [its source code](https://github.com/rust-lang/book/tree/main/packages/trpl).
You will then be able to see what crate each re-export comes from, and we have left extensive comments explaining what the crate does.
First we will start by building a little command line tools that fetches two we pages, pulls the `
` element from each and print out the title of whichever page finishes that whole process first.
## Defining the `page_title` Function
First we will start by writing a function that takes one page URL as a parameter
```rust
extern crate trpl; // required for mdbook test
fn main() {
// TODO: we'll add this next!
}
use trpl::Html;
async fn page_title(url: &str) -> Option {
let response = trpl::get(url).await;
let response_text = response.text().await;
Html::parse(&response_text)
.select_first("title")
.map(|title_element| title_element.inner_html())
}
```
Fist we define a fnction named `page_title` and mark it with the `async` keyword.
We then ise the `trpl::get` function to fetch whatever URL is passed in and add the `await` keyword to await the response.
To get the response, we call its `text` method, and once again await it with the `await` keyword.
Both of these steps are asynchronous.
For the `get` function, we have to wait for the server to send back the first part of its response. This will include HTTP header, cookies and so on, and can be delivered separately from the response body.
Especially if the body is very large, it can take some time for it all to arrive.
If we have to wait for the _entirety_ of the response to arrive, the `text` method is also aync.
Here we have to explicity await both of these future, because futures in Rust are _lazy_
Futures will not do anthing until you ask them to with the `await` keyword. (Rust will show a compiler warning if you don't use a future)
This might remind you of iterators in the section [Processing a Series of Items With Iteraors](./Iterators.md).
Iterators do nothing unless you call their `next` method whether directly or by using `for` loops or methods such as `map` that use `next` under the hood.
Likewise, futures do nothing unless you explicitly ask them to.
This laziness allows Rust ot avoid running async code until its actually needed.
This is differnt from the behavoir we say before when unsing `thread::spawn` in [Creating a New Thread with `spawn`](./Simultaneous%20Code%20Running.md#creating-a-new-thread-with-spawn), where the closure we passed to another thead started running immediately.
This is also different from how many other languages approach async.
This is improtant for Rust and we will see why later.
Once we have `response_text`, we can then parse it into an intance of the `Html` type using `Html::parse`.
Instead of a raw string, we now have a data type we can work with the HTML as a richer data structure.
In particular, we can use the `select_first` method to find the first instace of a given CSS selector.
By passing the string `"title"`, we get the first `` element in the document, if there is one.
Becuase there may not be any matching element, `select_first` returns an `Option`.
Lastly we use the `Option::map` method, this lets us work with the item in the `Option` if it is present and do nothing if it isn't.
We could also use a `match` expression, but `map` is more idiomatic.
In the body of the function we supply to `map`, we call `inner_html` on `title_element` to get its content, which is a `String`.
When it is all done we have an `Option`
Note that Rust's `await` kword goes _after_ the expression you are awaiting, not before it.
It is a _postfix_ keyword.
This may differ from what you may have used `async` in other languages, but in Rust it makes chains of methods much nice to work with.
This results that we can change the body of `page_url_for` to chain the `trpl::get` and `text` function calls together with `await` between them.
```rust
let response_text = trpl::get(url).await.text().await;
```
With this we have successfully written our first async function.
Befor we add some code in `main` to call it. We will dive even deep into what we have written and what it means.
When Rust sees a block mared with the `async` keyword, it compiles it into a unique, anonymous data tpye that implements the `Future` trait.
When Rust sees a function marked with `async`, it compiles it not a non-async function whose body is an async block.
An async function's return type is the type of the anonymous data type the compiler creates for that async block.
Writing `async fn` is equivalent to writing a function that returns a _future_ of the return type.
To the compiler, a function definition such as the `async fn page_title` is equivalent ot a non-async function defined like this:
```rust
use std::future::Future;
use trpl::Html;
fn page_title(url: &str) -> impl Future