How to Convert Between Sync and Async Code in Rust

Convert sync code to async in Rust by adding the async keyword to functions and using await to pause execution until futures complete.

Use the async keyword to define a function that returns a Future and the .await keyword to pause execution until that future completes.

use trpl::Html;

async fn page_title(url: &str) -> Option<String> {
    let response_text = trpl::get(url).await.text().await;
    Html::parse(&response_text)
        .select_first("title")
        .map(|title| title.inner_html())
}

To run this async code from a synchronous main function, you must use an async runtime like tokio to spawn the task and await its result.