[英]Rust: Async find (use await within predicate)
I am trying to use async within find predicates.我正在尝试在查找谓词中使用异步。 We can use the find method to look up an element within an iterator as follows:我们可以使用 find 方法在迭代器中查找元素,如下所示:
let element = some_elements.iter().find(|element| {
// some_async_method(element).await;
// true or false based on some logic
});
In my case, I need to call async methods as a part of my lookup logic.就我而言,我需要调用异步方法作为查找逻辑的一部分。 However, when I use await, I end up with the error that await cannot be called within non-async block, which is expected.但是,当我使用 await 时,我最终遇到无法在非异步块中调用 await 的错误,这是预期的。 When I try to make my function async as follows:当我尝试按如下方式使我的函数异步时:
let element = some_elements.iter().find(|element| async move{
// some_async_method(element).await;
// true or false based on some logic
});
I get the error: expected bool
, found opaque type我收到错误:预期bool
,发现不透明类型
I tried to to use rayon, but could not find an example for what I am looking for.我尝试使用人造丝,但找不到我正在寻找的示例。
You can use futures::stream::iter
to turn your iterator into a Stream
.您可以使用futures::stream::iter
将迭代器变成Stream
。
Since find
is not implemented on StreamExt
I replaced it with filter().next()
in the following:由于find
没有在StreamExt
上实现,我在下面用filter().next()
替换了它:
use futures::stream::StreamExt;
//…
let element = futures::stream::iter(&some_elements)
.filter(|e| Box::pin(async move { predicate(e).await }))
.next()
.await;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.