如何将 async fn 设置为 future

how to case async fn as future


async fn get_current_user(
    req: HttpRequest,
    payload: &mut Payload,
    config: &CurrentUserConfig,
) -> Result<CurrentUser, Error> {
    todo!()
}

#[derive(Debug)]
pub struct CurrentUser(User);

impl FromRequest for CurrentUser {
    type Error = Error;
    type Future = impl Future<Output = Result<Self, Self::Error>>;

    #[inline]
    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
        let config = CurrentUserConfig::from_req(req);
        get_current_user(req.clone(), payload, config)
    }
}

以上代码无法正常工作,因为'impl Trait' in type aliases is unstable, 我应该设置什么类型的Future

............................

你有些地方做错了。 查看 FromRequest 特征。

pub trait FromRequest: Sized {
    type Error: Into<Error>;
    type Future: Future<Output = Result<Self, Self::Error>>;
    type Config: Default + 'static;
    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future;

您返回的类型错误:

type Future: Future<Output = Result<Self, Self::Error>>;

您返回的是 User 而不是 CurrentUser

关于哪个类型的问题,可以用Box<dyn Future>.

impl FromRequest for CurrentUser {
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<CurrentUser, Error>>>>;
    type Config = ();
    fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
        let fut = get_token(&req);
        Box::pin(async move {
            let res: JwtToken = fut.await?;
            match res {
                JwtToken::User(user) => Ok(user),
                _ => Err(Error::Authentication),
            }
        })
    }
}