I'm using Rocket framework and I want to make an async HTTP request in my handler, something like this
#[get("/")]
async fn handler() -> String {
some_func().await;
"OK".into()
}
And as a result, I get the next error
the trait `rocket::response::Responder<'_>` is not implemented for `impl core::future::future::Future`
I tried to write implementation but failed. Is there a way to implement trait for impl Trait?
Or maybe specify the return type of async fn so I can return my custom type with necessary traits implemented?
Rocket is a web framework that is built on top of Tokio. It uses async Rust and does a lot of our work for us. Rocket has some magical type macros that let us specify the inputs to our request handlers as normal Rust structs.
async transforms a block of code into a state machine that implements a trait called Future . Whereas calling a blocking function in a synchronous method would block the whole thread, blocked Future s will yield control of the thread, allowing other Future s to run. The value returned by async fn is a Future .
Until Rocket 0.5.0 is released you will have to use the development version for async routes. Notably this also means you can use stable Rust to compile.
In your Cargo.toml
rocket = { git = "https://github.com/SergioBenitez/Rocket" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket" }
Once using the development version you can write async routes exactly as you've done so in the question.
Note that various APIs may be different. See https://api.rocket.rs/master/rocket/index.html for documentation for the development version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With