Skip to content

How to use async/await in iter map? #4346

Answered by Darksonn
lz1998 asked this question in Q&A
Discussion options

You must be logged in to vote

The way to do this is to use a Stream rather than an Iterator. Streams have a method similar to map called then which lets you perform async operations.

use futures::stream::StreamExt;

async fn http_get_data(id: i32) -> String {
    id.to_string()
}

#[tokio::main]
async fn main() {
    let ids = vec![1, 2, 3];
    let data: Vec<_> = futures::stream::iter(ids)
        .then(|id| async move {
            http_get_data(id).await
        })
        .collect()
        .await;

    println!("{:?}", data);
}

Note that the async block is not actually necessary in this particular example:

let data: Vec<_> = futures::stream::iter(ids)
    .then(|id| http_get_data(id))
    .collect()
    .await;

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@lz1998
Comment options

@Darksonn
Comment options

Answer selected by lz1998
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants