#![allow(dead_code)]
// Some async op. E.g., access database.
async fn do_some_async(_num: i32) -> bool {
true
}
// How to run async code within a long Option / Result function chain?
// E.g., value.and_then(...).or_else(...).map(...)
// First try:
async fn not_work1(input: Option<i32>) -> Option<i32> {
input
.and_then(|num| {
if do_some_async(num).await { // not work, can not use `.await`
// because not in async block
Some(42)
} else {
None
}
})
}
// Second try:
async fn not_work2(input: Option<i32>) -> Option<u32> {
input
.and_then(|num| async { // add async here
// not work, return `impl Future` but not Option
if do_some_async(num).await {
Some(42)
} else {
None
}
})
}
// This one work: but I don't want to expand op to outer scope all the time...
async fn work(input: Option<i32>) -> Option<u32> {
match input {
Some(num) => {
if do_some_async(num).await {
Some(42)
} else {
None
}
}
None => None
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src/lib.rs:15:16
|
14 | .and_then(|num| {
| ----- this is not `async`
15 | if do_some_async(num).await { // not work, can not use `.await`
| ^^^^^^^^^^^^^^^^^^^^^^^^ only allowed inside `async` functions and blocks
error[E0308]: mismatched types
--> src/lib.rs:27:25
|
27 | .and_then(|num| async { // add async here
| _________________________^
28 | | // not work, return `impl Future` but not Option
29 | | if do_some_async(num).await {
30 | | Some(42)
... |
33 | | }
34 | | })
| |_________^ expected enum `Option`, found opaque type
|
= note: expected enum `Option<_>`
found opaque type `impl Future`
help: try using a variant of the expected enum
|
27 | .and_then(|num| Some(async { // add async here
28 | // not work, return `impl Future` but not Option
29 | if do_some_async(num).await {
30 | Some(42)
31 | } else {
32 | None
...
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0308, E0728.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `playground`
To learn more, run the command again with --verbose.
I feel I need to convert Option
/ Result
to some async compatible things, maybe futures crate have them but I'm not sure what I'm looking for. Any suggestion?