我有一个下载异步文件的函数:
async fn download_file() {
fn main() {
let resp = reqwest::blocking::get("https://sh.rustup.rs").expect("request failed");
let body = resp.text().expect("body invalid");
let mut out = File::create("rustup-init.sh").expect("failed to create file");
io::copy(&mut body.as_bytes(), &mut out).expect("failed to copy content");
}
}
Run Code Online (Sandbox Code Playgroud)
我想调用这个函数来下载文件,然后在需要时等待它。
但问题是,如果我这样做,我会得到一个错误:
fn main() {
let download = download_file();
// Do some work
download.await; // `await` is only allowed inside `async` functions and blocks\nonly allowed inside `async` functions and blocks
// Do some work
}
Run Code Online (Sandbox Code Playgroud)
所以我必须使 main 函数异步,但是当我这样做时,我收到另一个错误:
async fn main() { // `main` function …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用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(); …Run Code Online (Sandbox Code Playgroud)