我正在尝试使用hyper来获取HTML页面的内容,并希望同步返回未来的输出。我意识到我可以选择一个更好的例子,因为已经存在同步HTTP请求,但我更感兴趣的是了解我们是否可以从异步计算中返回一个值。
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio;
use futures::{future, Future, Stream};
use hyper::Client;
use hyper::Uri;
use hyper_tls::HttpsConnector;
use std::str;
fn scrap() -> Result<String, String> {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get("https://hyper.rs".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
futures::future::ok(s_body)
})
}).map_err(|err| format!("Error scraping web page: {:?}", &err))
});
scraped_content.wait()
}
fn read() {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get("https://hyper.rs".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
println!("Reading body: {}", s_body);
Ok(())
})
}).map_err(|err| {
println!("Error reading webpage: {:?}", &err);
})
});
tokio::run(scraped_content);
}
fn main() {
read();
let content = scrap();
println!("Content = {:?}", &content);
}
该示例编译并且对read()
的调用成功,但对scrap()
的调用发生以下错误消息:
Content = Err("Error scraping web page: Error { kind: Execute, cause: None }")
我知道我未能在未来调用.wait()
之前正确启动任务但我无法找到如何正确地执行它,假设它甚至可能。
让我们用它作为我们的minimal, reproducible example:
use futures::future; // 0.3.0-alpha.17
use std::future::Future;
fn example() -> impl Future<Output = i32> {
future::ready(42)
}
fn main() {
let v = futures::executor::block_on(example());
println!("{}", v);
}
让我们用它作为我们的minimal, reproducible example:
use futures::{future, Future}; // 0.1.27
fn example() -> impl Future<Item = i32, Error = ()> {
future::ok(42)
}
对于简单的情况,您只需要调用wait
:
fn main() {
let s = example().wait();
println!("{:?}", s);
}
然而,这带来了非常严重的警告:
此方法不适合调用事件循环或类似的I / O情况,因为它会阻止事件循环进行(这会阻塞线程)。只有在保证与此未来相关的阻塞工作将由另一个线程完成时,才应调用此方法。
如果你使用的是Tokio,你应该使用Tokio的Runtime::block_on
:
use tokio; // 0.1.21
fn main() {
let mut runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime");
let s = runtime.block_on(example());
println!("{:?}", s);
}
如果您查看block_on
的实现,它实际上将未来的结果发送到一个通道,然后在该通道上调用wait
!这很好,因为Tokio保证将来完成运行。
也可以看看: