8
votes

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?

2

2 Answers

8
votes

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.

3
votes

As of Rocket v0.4, it is still not possible to describe handlers using async functions, though there are plans for Rocket to migrate to a full asynchronous environment in the future (see issue #1065).

Until this migration is done, one cannot handle futures in Rocket effectively. Workarounds may include adding your own executor and blocking on the completion of a future emerging from the handler (which definitely does not benefit from async as much as one could).