作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有什么方法可以在回调中使用 future 吗?例如...
// Send message on multiple channels while removing ones that are closed.
use smol::channel::Sender;
...
// (expecting bool, found opaque type)
vec_of_sender.retain( |sender| async {
sender.send(msg.clone()).await.is_ok()
});
我的解决方法是循环两次:在第一遍中,我删除关闭的发件人(非异步),在第二遍中,我进行实际的发送(使用
for sender in ...
异步)。但是似乎我应该可以在一个
retain()
调用中完成所有操作。
最佳答案
您不能以这种方式使用retain
。 retain
接受的闭包必须实现FnMut(&T) -> bool
,但是每个async
函数都返回Future
的实现。
您可以通过阻止异步功能将其转变为同步功能。例如,如果您使用的是tokio
,则可以执行以下操作:
use tokio::runtime::Runtime;
let rt = Runtime::new().unwrap();
vec_of_sender.retain(|sender| {
rt.block_on(async { sender.send().await.is_ok() })
});
但是,添加异步运行时会产生开销,并且我感觉到您正在尝试解决错误的问题。
关于asynchronous - 如何在回调中使用Rust future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65241788/
我是一名优秀的程序员,十分优秀!