为什么带有hyper / reqwest请求的try_ready!()永远不会完成?

时间:2019-05-01 07:57:20

标签: rust rust-tokio hyper

我使用hyper / reqwest来获取api结果的原因是impl for Future,但try_ready!()从未完成。

我尝试直接将hyper / reqwest与tokio::run()一起使用,或者将try_ready!()与hyper / request以外的其他东西一起使用。都没有挂起。

例如,下面的代码打印出j0j1,但挂在j2上。

use futures::{try_ready, Async, Future, Poll};
use hyper::rt::Stream;
use hyper::{Client, Uri};
use serde_json::Value;

fn fetch() -> impl Future<Item = Value, Error = ()> {
    let client = Client::new();
    client
        .get(Uri::from_static("http://httpbin.org/ip"))
        .and_then(|res| res.into_body().concat2())
        .and_then(|body| Ok(serde_json::from_slice(&body).unwrap()))
        .map_err(|_| ())
}

fn test_fn() -> impl Future<Item = (), Error = ()> {
    fetch().and_then(|j| {
        println!("j0 {:?}", j);
        Ok(())
    })
}

struct Fetch;
impl Future for Fetch {
    type Item = Value;
    type Error = ();
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        Ok(Async::Ready(Value::default()))
    }
}

struct Test;
impl Future for Test {
    type Item = ();
    type Error = ();
    fn poll(&mut self) -> Result<Async<()>, ()> {
        let j = try_ready!(Fetch.poll());
        println!("j1 {:?}", j);

        let j = try_ready!(fetch().poll());
        println!("j2 {:?}", j);

        Ok(Async::Ready(()))
    }
}

fn main() {
    println!("start");
    tokio::run(test_fn());
    tokio::run(Test);
}

0 个答案:

没有答案