Sync closures and async confusion

How do I write the following function using unwrap_or_else ?

    // This works
    pub async fn from_cache_or_synced () -> Result<Self, Error> {
        match Self::from_cache() {
            Ok(redorg) => Ok(redorg), // I don't like this
            Err(_) => {
                let mut redorg_init = Self::new();

This does not work and I don't understand why?

    pub async fn from_cache_or_synced2 () -> Result<Self, Error> {
        let redorg = Self::from_cache().unwrap_or_else( |_| async {
            let mut redorg_init = Self::new();

It says expected struct Redorg, found opaque type Future.

The result of an async expression is a Future. When you write an async fn, and you perform .await directly inside the function body, then you can pretend you are writing normal code and the types are what they appear to be; your return value (or more precisely, the computation representing your return value in the future) will be implicitly wrapped in a Future by the compiler.

This is also true in a closure: when you have an async block in your closure, and you do .await in it, then you will get back a Future from it. So the type of redorg itself will be Future<Output = Self>, therefore Ok(redord) has type Result<Future<…>>, and not Result<Self>.

You probably meant Ok(redorg.await).

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.