Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

asynchronous - How to use predicates in an async function?

I use thirtyfour in my Rust script, and it uses tokio as the async runtime.

When I use find in a Vec::iter, it doesn't work as I expect:

#[tokio::main]
async fn main() -> WebDriverResult<()> {
    let dropdown = driver.find_element(By::Tag("select")).await?;
    dropdown
        .find_elements(By::Tag("option"))
        .await?
        .iter()
        .find(|&&x| x.text() == book_time.date) // Error, x.text() return a futures::Future type while book_time.date return a &str.
        .click()
        .await?;
}

After I tried Ibraheem Ahmed's solution, I met more errors:

let dropdown = driver.find_element(By::Tag("select")).await?;
let elements = dropdown.find_elements(By::Tag("option")).await?;
let stream = stream::iter(elements);
let elements = stream.filter(|x| async move { x.text().await.unwrap() == target_date });
error: lifetime may not live long enough
   --> srcmain.rs:125:38
    |
125 |     let elements = stream.filter(|x| async move { x.text().await.unwrap() == target_date });
    |                                   -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
    |                                   ||
    |                                   |return type of closure is impl futures::Future
    |                                   has type `&'1 thirtyfour::WebElement<'_>`
question from:https://stackoverflow.com/questions/65912105/how-to-use-predicates-in-an-async-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a Stream, which is the asynchronous version of Iterator:

use futures::stream::{self, StreamExt};

fn main() {
    // ...
    let stream = stream::iter(elements).await?;
    let elements = stream
        .filter(|x| async move { x.text().await.as_deref() == Ok(book_time.date) })
        .next()
        .click()
        .await?;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...