对具有不同误差类型的两个独立期货进行排序



我的代码排列如下:-

let done = client_a.
.get_future(data)
.then(move |result| {
// further processing on result
spawn a future here.
});
tokio::run(done);

现在我有另一个未来,我想与"结果的处理"一起处理结果。 然而,这个未来完全独立于client_a这意味着:-

  • 两者都可能具有不同的错误类型。
  • 一个失败不应该阻止另一个。

    let done = client_a.
    .get_future(data)
    .then(move |result| {
    // how to fit in 
    // client_b.get_future
    // here
    // further processing on both results
    spawn third future here.
    });
    tokio::run(done);
    

如果错误和项目类型都是异构的,并且你知道你将链接多少个期货,最简单的方法是链接到一个绝对可靠的Future(因为这就是你剩下的未来(,其Item类型是所有中间结果的元组。

这可以通过简单的链接相对简单地实现:

let future1_casted = future1.then(future::ok::<Result<_, _>, ()>);
let future2_casted = future2.then(future::ok::<Result<_, _>, ()>);
let chain = future1_casted
.and_then(|result1| future2_casted.map(|result2| (result1, result2)));

游乐场链接

最终的未来类型是包含期货所有结果的元组。

如果您不知道要链接多少期货,则需要加强您的要求,并提前明确了解期货可能的回报类型。由于没有宏就不可能生成任意大小的元组,因此您需要将中间结果存储到需要同类类型的结构中。

要解决此问题,需要定义包含类型的元组,例如错误元组:

#[derive(PartialEq, Debug)]
pub enum MyError {
Utf16Error(char::DecodeUtf16Error),
ParseError(num::ParseIntError)
}
impl From<char::DecodeUtf16Error> for MyError {
fn from(e: char::DecodeUtf16Error) -> Self {
MyError::Utf16Error(e)
}
}
impl From<num::ParseIntError> for MyError {
fn from(e: num::ParseIntError) -> Self {
MyError::ParseError(e)
}
}

从那里开始,组合期货遵循与以前相同的路线 - 将易犯错的未来变成绝对可靠的Result<_, _>回报,然后结合成一个结构,如Vecfuture::loop_fn()

最新更新