如何从包含期货的结果中创建期货?

allsey87

是否可以(逻辑上)将包含未来的结果转换为可以解决结果的未来?

以下功能有些破损,但希望可以使我试图实现的目的更加清楚:

use std::future::Future;

fn transpose<T,U,E>(result: Result<T,E>) -> impl Future<Output = Result<U, E>>
   where T: Future<Output = Result<U,E>> /* not sure if this is the correct trait bound */ {
   match result {
      Ok(inner) => /* a future that eventually resolves to a Result<U, E> */
      Err(error) => /* a future that immediately resolves to a Result<U, E>::Err(error) */
   }
}

给出一些背景信息:在async从传递给的闭包中调用函数之后,我发现自己需要这样做Result::map,所以也许这是我的第一个错误。

特伦特

通常,人们通常想要的是Err立即处理此案,而不是等到.awaited将来,这样才能解释为什么这样的功能还不存在。但是,如果确实需要,则使用async编写代码非常简单.await

fn transpose_flatten<T, U, E>(result: Result<T, E>) -> impl Future<Output = Result<U, E>>
where
    T: Future<Output = Result<U, E>>,
{
    async {                          // when polled,
        match result {
            Ok(good) => good.await,  // defer to the inner Future if it exists
            Err(bad) => Err(bad),    // otherwise return the error immediately
        }
    }
}

或使用相同的东西async fn(并不总是完全相同的东西,但在这种情况下,似乎是这样):

async fn transpose_flatten<T, U, E>(result: Result<T, E>) -> Result<U, E>
where
    T: Future<Output = Result<U, E>>,
{
    match result {
        Ok(good) => good.await,
        Err(bad) => Err(bad),
    }
}

transpose_flatten之所以调用此函数,是因为transpose它听起来像应该带一个Result<Future<Output = U>, _>此函数展平了两层Result(一层传递给该函数,另一层从将来返回)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章