< 返回版块

WorldLink 发表于 2020-12-16 19:30

Tags:async,async_std,tokio

use super::*;
use std::fmt::Debug;
use async_std::future::Future;


/// Middleware handle function
#[async_trait]
pub trait Middleware<State: Clone + Send + Sync + 'static> {
    /// 具体实现方法
    async fn handle(&self, ctx: Context<State>);
}

#[async_trait]
impl<State, F> Middleware<State> for F
    where
        State: Clone + Send + Sync + 'static,
        F: Send + Sync + 'static + Fn(Context<State>),
{
    async fn handle(&self, ctx: Context<State>) {
        let fut = (self)(ctx);
        fut.await;
    }
}
error[E0277]: `()` is not a future
  --> src/http/middleware.rs:21:9
   |
21 |         fut.await;
   |         ^^^^^^^^^ `()` is not a future
   |
   = help: the trait `std::future::Future` is not implemented for `()`
   = note: required by `std::future::Future::poll`

很纳闷这个怎么实现???

我看到tide框架 这样写没有报错的???

#[async_trait]
pub trait Endpoint<State: Clone + Send + Sync + 'static>: Send + Sync + 'static {
    /// Invoke the endpoint within the given context
    async fn call(&self, req: Request<State>) -> crate::Result;
}

pub(crate) type DynEndpoint<State> = dyn Endpoint<State>;

#[async_trait]
impl<State, F, Fut, Res> Endpoint<State> for F
where
    State: Clone + Send + Sync + 'static,
    F: Send + Sync + 'static + Fn(Request<State>) -> Fut,
    Fut: Future<Output = Result<Res>> + Send + 'static,
    Res: Into<Response> + 'static,
{
    async fn call(&self, req: Request<State>) -> crate::Result {
        let fut = (self)(req);
        let res = fut.await?;
        Ok(res.into())
    }
}

评论区

写评论
作者 WorldLink 2020-12-17 10:22

小弟太菜真是抱歉

#[async_trait]
impl<State, F, Fut> Middleware<State> for F
    where
        State: Clone + Send + Sync + 'static,
        F: Send + Sync + 'static + Fn(Context<State>) -> Fut,
        Fut: Future<Output = ()> + Send + 'static,
{
    async fn handle(&self, ctx: Context<State>) {
        let fut = (self)(ctx);
        fut.await
    }
}

这样就行

--
👇
Aya0wind: 人家的Fn返回的是Fut,是个impl future类型,你这Fn返回的是个空,能一样吗?你这段代码连future的影子都没有,怎么await。

Aya0wind 2020-12-16 22:32

人家的Fn返回的是Fut,是个impl future类型,你这Fn返回的是个空,能一样吗?你这段代码连future的影子都没有,怎么await。

作者 WorldLink 2020-12-16 19:42
#[async_trait]
impl<State, F> Middleware<State> for F
    where
        State: Clone + Send + Sync + 'static,
        F: Send + Sync + 'static + Fn(Context<State>),
{
    async fn handle(&self, ctx: Context<State>) {
        let fut = (self)(ctx);
        fut.await
    }
}
error[E0277]: `()` is not a future
  --> src/http/middleware.rs:21:9
   |
21 |         fut.await
   |         ^^^^^^^^^ `()` is not a future
   |
   = help: the trait `std::future::Future` is not implemented for `()`
   = note: required by `std::future::Future::poll`

大佬 去掉了分号还是???

👇
Ryan-Git: 末尾不要分号

Ryan-Git 2020-12-16 19:34

末尾不要分号

1 共 4 条评论, 1 页