Async in a closure

Can I handle async in some closures like following this?

let result: Result<u8, ()> = Ok(1);
let fold: u8 = result.map_or_else(
    |_error| { 
        async { 
            let ten = ten().await;
            ten + 5
        }
    },
    |value| { async { value } }
).await;

async fn ten() -> u8 {
    10
}

Rust compiler says expected async block, found a different async block, so I'm searching the way how to avoid the error.

1 Like

I'd convert your Result to a Future by using futures::future::ready. That allows you to use the extension methods of futures::future::TryFutureExt, some of which (like or_else) allowing you to return a future from your closure. Example.

4 Likes

Yes, you can use future::Either:

use futures::future::Either;

#[tokio::main]
async fn main () {
    let result: Result<u8, ()> = Ok(1);
    let fold: u8 = result.map_or_else(
        |_error| { 
            Either::Left(async { 
                let ten = ten().await;
                ten + 5
            })
        },
        |value| { Either::Right(async move { value }) }
    ).await;
    
    async fn ten() -> u8 {
        10
    }
}
5 Likes

Nice! I appreciate your help.
I didn't know futures::future::ready makes help us to solve the problem!
Thank you for your solution🎉

I didn't know Either can combine two async blocks!
My production code also looks good using yours.
That's the solution that I want. Thank you very much🎉

Both solutions are equivalent in the sense that both use combinators, it's just a matter of whether you use the combinators from Result or from Future via the TryFutureExt extension trait.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.