gpt4 book ai didi

asynchronous - 如何转换 future 的输出?

转载 作者:行者123 更新时间:2023-11-29 08:26:20 26 4
gpt4 key购买 nike

使用 Tokio 的 future ,如果你想转换 Error在组合器的因果链中,您使用 from_err::<NewType>() .我想要相同的功能,但不是 Itemimpl Future<Item = (), Error = ()> .

我的一些代码示例:

let mut async_series_client = vec![];
async_series_client.push(Box::new(
SocketHandler::connect(
port,
addr,
handle,
tx_wave,
tx_linear,
KcpSessionManager::new(&handle2).unwrap(),
)
.from_err::<HyxeError>()
.join(tube)
.map_err(|mut err| err.printf()),
));

返回 ((),()) (附带问题:它是否因为连接而返回 () 的元组?)。我希望它只返回 () .我该怎么做?

最佳答案

使用Future::map .这与 Option::mapResult::mapIterator::map 平行:

use futures::{future, Future}; // 0.1.27

fn some_future() -> impl Future<Item = i32, Error = ()> {
future::ok(42)
}

fn change_item() -> impl Future<Item = String, Error = ()> {
some_future().map(|i| i.to_string())
}

另见 Stream::map .


async/await 语法稳定后,您可能再也不需要使用此组合器,因为您可以使用普通方法:

async fn some_future() -> i32 {
42
}

async fn change_output() -> String {
some_future().await.to_string()
}

或者Result::map:

async fn some_future() -> Result<i32, ()> {
Ok(42)
}

async fn change_output() -> Result<String, ()> {
some_future().await.map(|i| i.to_string())
}

但它仍然存在:

use futures::{Future, FutureExt}; // 0.3.0-alpha.16

async fn some_future() -> i32 {
42
}

fn change_output() -> impl Future<Output = String> {
some_future().map(|i| i.to_string())
}

关于asynchronous - 如何转换 future 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com