Allow racing two URL fetch tasks against each other
This commit is contained in:
parent
9e59d39384
commit
97ae7598ce
1 changed files with 20 additions and 10 deletions
|
@ -1,20 +1,30 @@
|
||||||
use trpl::Html;
|
use trpl::{Either, Html};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let args: Vec<String> = std::env::args().collect();
|
let args: Vec<String> = std::env::args().collect();
|
||||||
|
|
||||||
trpl::run(async {
|
trpl::run(async {
|
||||||
let url = &args[1];
|
let title_fut_1 = page_title(&args[1]);
|
||||||
match page_title(url).await {
|
let title_fut_2 = page_title(&args[2]);
|
||||||
Some(title) => println!("The title for {url} was {title}"),
|
|
||||||
None => println!("{url} had no title"),
|
let (url, maybe_title) =
|
||||||
|
match trpl::race(title_fut_1, title_fut_2).await {
|
||||||
|
Either::Left(left) => left,
|
||||||
|
Either::Right(right) => right,
|
||||||
|
};
|
||||||
|
|
||||||
|
println!("{url} returned first");
|
||||||
|
match maybe_title {
|
||||||
|
Some(title) => println!("Its page title is: '{title}'"),
|
||||||
|
None => println!("Its title could not be parsed."),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn page_title(url: &str) -> Option<String> {
|
async fn page_title(url: &str) -> (&str, Option<String>) {
|
||||||
let response_text = trpl::get(url).await.text().await;
|
let text = trpl::get(url).await.text().await;
|
||||||
Html::parse(&response_text)
|
let title = Html::parse(&text)
|
||||||
.select_first("title")
|
.select_first("title")
|
||||||
.map(|title_element| title_element.inner_html())
|
.map(|title| title.inner_html());
|
||||||
}
|
(url, title)
|
||||||
|
}
|
Loading…
Reference in a new issue