実現したいこと
axumのハンドラーの中で、async関数を実行した結果を元に処理を行い、その後、別のasync関数を実行したい。
rust
1 let res1 = test1().await; 2 match res1 { 3 Ok(_) => { 4 // 処理1 5 } 6 Err(error) => { 7 // 処理2 8 } 9 } 10 let _ = test2().await;
発生している問題・分からないこと
以下のようにaxumのハンドラーの中で返り値があるasync/awaitの関数を連続して実行しようとするとエラーになります。
rust
1async fn handle_index()-> StatusCode { 2 let res1 = test1().await; 3 let res2 = test2().await; 4 StatusCode::OK 5} 6 7async fn test1()-> Result<(), Box<dyn std::error::Error>> { 8 Ok(()) 9} 10async fn test2()-> Result<(), Box<dyn std::error::Error>> { 11 Ok(()) 12}
エラーメッセージ
error
1error[E0277]: the trait bound `fn() -> impl Future<Output = axum::http::StatusCode> {handle_index}: Handler<_, _>` is not satisfied 2 --> src/main.rs:70:25 3 | 470 | .route("/", get(handle_index)) 5 | --- ^^^^^^^^^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn() -> impl Future<Output = axum::http::StatusCode> {handle_index}` 6 | | 7 | required by a bound introduced by this call 8 | 9 = note: Consider using `#[axum::debug_handler]` to improve the error message 10 = help: the following other types implement trait `Handler<T, S>`: 11 `Layered<L, H, T, S>` implements `Handler<T, S>` 12 `MethodRouter<S>` implements `Handler<(), S>` 13note: required by a bound in `axum::routing::get` 14 --> /hoge/hoge/.cargo/registry/src/index.crates.io-6f17d22bba15001f/axum-0.8.1/src/routing/method_routing.rs:440:1 15 | 16440 | top_level_handler_fn!(get, GET); 17 | ^^^^^^^^^^^^^^^^^^^^^^---^^^^^^ 18 | | | 19 | | required by a bound in this function 20 | required by this bound in `get` 21 = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) 22 23For more information about this error, try `rustc --explain E0277`.
該当のソースコード
特になし
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
最初の呼び出しで、返り値を let _ = とすればエラーが消える。ただし、これはやりたいことではない。
rust
1async fn handle_index()-> StatusCode { 2 let _ = test1().await; 3 let res2 = test2().await; 4 StatusCode::OK 5}
async/awaitでない場合もエラーが消える。ただし、asyncで実行したいです。
rust
1async fn handle_index()-> StatusCode { 2 let res1 = test1(); 3 let res2 = test2(); 4 StatusCode::OK 5} 6 7fn test1()-> Result<(), Box<dyn std::error::Error>> { 8 Ok(()) 9} 10fn test2()-> Result<(), Box<dyn std::error::Error>> { 11 Ok(()) 12}
axumではなく、通常のsrc/main.rs内で$ cargo run した場合は、返り値があるasync/awaitの関数を連続して実行してもエラーにはなりませんでした。
補足
axumのバージョンは"0.8.1"です。

回答1件
あなたの回答
tips
プレビュー