many-requests-surf: Add example from Chapter 20, Asynchronous Programming.
parent
165ec30977
commit
d4dff688ee
@ -0,0 +1 @@
|
|||||||
|
/target/
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,11 @@
|
|||||||
|
[package]
|
||||||
|
name = "many-requests-surf"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["You <you@example.com>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
async-std = "1.7"
|
||||||
|
surf = "1.0"
|
@ -0,0 +1,32 @@
|
|||||||
|
pub async fn many_requests(urls: &[String])
|
||||||
|
-> Vec<Result<String, surf::Exception>>
|
||||||
|
{
|
||||||
|
let client = surf::Client::new();
|
||||||
|
|
||||||
|
let mut handles = vec![];
|
||||||
|
for url in urls {
|
||||||
|
let request = client.get(&url).recv_string();
|
||||||
|
handles.push(async_std::task::spawn(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut results = vec![];
|
||||||
|
for handle in handles {
|
||||||
|
results.push(handle.await);
|
||||||
|
}
|
||||||
|
|
||||||
|
results
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let requests = &["http://example.com".to_string(),
|
||||||
|
"https://www.red-bean.com".to_string(),
|
||||||
|
"https://en.wikipedia.org/wiki/Main_Page".to_string()];
|
||||||
|
|
||||||
|
let results = async_std::task::block_on(many_requests(requests));
|
||||||
|
for result in results {
|
||||||
|
match result {
|
||||||
|
Ok(response) => println!("*** {}\n", response),
|
||||||
|
Err(err) => eprintln!("error: {}\n", err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue