9

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?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
KonstantinB
  • 115
  • 1
  • 3
  • 8

3 Answers3

8

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.

jla
  • 4,191
  • 3
  • 27
  • 44
3

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).

E_net4
  • 27,810
  • 13
  • 101
  • 139
2

As of 2022, this is straightforward:

Rocket makes it easy to use async/await in routes.

use rocket::tokio::time::{sleep, Duration};

#[get("/delay/<seconds>")]
async fn delay(seconds: u64) -> String {
    sleep(Duration::from_secs(seconds)).await;
    format!("Waited for {} seconds", seconds)
}
jnnnnn
  • 3,889
  • 32
  • 37