How do I convert an async / standard library future to futures 0.1?

前端 未结 1 1661
不思量自难忘°
不思量自难忘° 2020-12-11 22:00

I want to use the async function to parse the inbound stream progressively, but actix-web requires impl Future

相关标签:
1条回答
  • 2020-12-11 23:02

    std::future -> future@0.1 conversion steps:

    • The future needs to be TryFuture (Output = Result<T, E>)
    • The future needs to be Unpin (you can use boxed combinator)
    • Finally, you can call the compat combinator

    Your inbound function:

    fn inbound(
        req: HttpRequest,
        stream: web::Payload,
    ) -> impl Future<Item = HttpResponse, Error = Error> {
        let fut = async_inbound(&req, &stream);
        fut.unit_error().boxed_local().compat()
    }
    

    The inbound function signature is fine, but the conversion isn't.

    The async_inbound function isn't TryFuture (because of -> HttpResponse). You're trying to convert it with the unit_error combinator, but the result is Result<HttpResponse, ()> and you want Result<HttpResponse, Error>. Fixed inbound function:

    fn inbound(
        req: HttpRequest,
        stream: web::Payload,
    ) -> impl Future<Item = HttpResponse, Error = Error> {
        let fut = async_inbound(req, stream);
        fut.boxed_local().compat()
    }
    

    Your async_inbound function:

    async fn async_inbound(req: &HttpRequest, stream: &web::Payload) -> HttpResponse {
        // ...
    }
    

    The first issue here is to replace -> HttpResponse with -> Result<HttpResponse>. Another problem is that you're passing reg and stream by reference. Move them as there's no need to take a reference and you'll need 'static. Fixed async_inbound function:

    async fn async_inbound(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse> {
        let mut compat_stream = stream.compat();
    
        while let Some(data) = compat_stream.try_next().await? {
            println!("{:?}", data);
        }
    
        Ok(HttpResponse::Ok().content_type("text/html").body("RESP"))
    }
    
    0 讨论(0)
提交回复
热议问题