i have a vector i want to iterate over and use map to call an async function (see code below).
However, i keep getting compile error - please see fn sum below
How do i get the code to compile?
Code Sample:
#[derive(Debug)]
struct B { val: u32 }
impl B {
pub async fn do_b(&self) -> Result<u32, anyhow::Error> { Ok(1) }
pub fn do_c(&self) -> Result<u32, anyhow::Error> {Ok(2)}
}
// sum() is async, why can't i call await?
async fn sum(arr: Vec<B>) -> Result<u32, anyhow::Error> {
// can't compile - Error A - fn sum is an async fn, why can't i call await?
// error[E0728]: `await` is only allowed inside `async` functions and blocks
let values: Vec<Result<u32, anyhow::Error>> = arr.iter().map(|b| b.do_b().await? ).collect();
// can't compile - Error B - tried to wrap call in async block
// error[E0277]: the `?` operator can only be used in an async block that returns `Result` or `Option` (or another type that implements `FromResidual`)
let values: Vec<Result<u32, anyhow::Error>> = arr.iter().map(|b| async { b.do_b().await? } ).collect();
// my sanity check -can compile
let values: Vec<Result<u32, anyhow::Error>> = arr.iter().map(|b| b.do_c()).collect();
B{val:0}.do_b().await?; // sanity check - can compile
Ok(0)
}
Error-A:
error[E0728]: `await` is only allowed inside `async` functions and blocks
|
41 | let values: Vec<Result<u32, anyhow::Error>> = arr.iter().map(|b| b.do_b().await? ).collect(); // can't compile - Error A
| --- ^^^^^^^^^^^^^^ only allowed inside `async` functions and blocks
| |
| this is not `async`
Error-B:
error[E0277]: the `?` operator can only be used in an async block that returns `Result` or `Option` (or another type that implements `FromResidual`)
|
42 | let values: Vec<Result<u32, anyhow::Error>> = arr.iter().map(|b| async { b.do_b().await? } ).collect(); // can't compile - Error B
| ----------------^--
| | |
| | cannot use the `?` operator in an async block that returns `u32`
| this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Result<Infallible, anyhow::Error>>` is not implemented for `u32`
note: required by `from_residual`
|
339 | fn from_residual(residual: R) -> Self;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^