rust tokio中Future的使用疑惑

新手上路,请多包涵

使用tokio时把hyper client发送get请求,为什么第一种方法可以直接返回,第二种方法却一直阻塞!

方法一:

//main方法

tokio::run(lazy(|| {
        let url = String::from("http://www.baidu.com").parse::<hyper::Uri>().unwrap();
        let client = Client::new().get(url).map_err(|_| ProcessError::GetRequestError).and_then(|res| {
            println!("{}",res.status());
            return future::ok(());    
        }).map_err(|_| ());
        return client;
    }));

第二种方法

impl Future for DocumentBuilder {
    type Item = RcDom;
    type Error = ProcessError;
    fn poll(&mut self) -> Poll<Self::Item,Self::Error> {
        let response = self.client.get(self.uri.clone());
        let body = response.wait();
        if body.is_ok() {
            println!("is ok!");
        } else {
            println!("err");
        }
        panic!("..");
    }
}
tokio::run(lazy(|| {
        let document = DocumentBuilder::new("https://www.baidu.com").unwrap().map_err(|err| {
            println!("{:?}",err);
        }).map(|_| {
            println!("..");
        });
        return document;
    }));

第二种方法为什么不能panic,而是一直wait

阅读 4k
1 个回答
use futures::{Future, Poll};
use hyper::{client::ResponseFuture, Client, Uri};

struct MyFuture {
    future: ResponseFuture,
}

impl MyFuture {
    fn new() -> MyFuture {
        MyFuture {
            future: Client::new().get(Uri::from_static("http://www.baidu.com")),
        }
    }
}

impl Future for MyFuture {
    type Item = <ResponseFuture as Future>::Item;
    type Error = <ResponseFuture as Future>::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.future.poll()
    }
}

fn main() {
    let fut = MyFuture::new();
    tokio::run(fut.map_err(|_| ()).map(|res| {
        println!("res: {:?}", res);
    }));
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进