首页 > 解决方案 > 我可以在 Rocket 中使用异步 fn 作为处理程序吗?

问题描述

我正在使用 Rocket 框架,我想在我的处理程序中发出一个异步 HTTP 请求,就像这样

#[get("/")]
async fn handler() -> String {
  some_func().await;
  "OK".into()
}

结果,我得到了下一个错误

the trait `rocket::response::Responder<'_>` is not implemented for `impl core::future::future::Future`

我试图编写实现但失败了。有没有办法为 impl Trait 实现 trait?

或者也许指定 async fn 的返回类型,以便我可以返回具有必要特征的自定义类型?

标签: rustasync-awaittraitsrust-rocket

解决方案


在 Rocket 0.5.0 发布之前,您必须将开发版本用于异步路由。值得注意的是,这也意味着您可以使用稳定的 Rust 进行编译。

在你的 Cargo.toml

rocket = { git = "https://github.com/SergioBenitez/Rocket" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket" }

使用开发版本后,您可以完全按照您在问题中所做的那样编写异步路由。

请注意,各种 API 可能不同。有关开发版本的文档,请参阅https://api.rocket.rs/master/rocket/index.html


推荐阅读