How to await for all futures created inside a loop

I am trying to download a few files inside a loop:

let j = reqwest::get(&link.api)
        .expect("HTTP GET error")
        .expect("Deserialization error");

    for post in j.posts {
        match (post.tim, post.ext) {
            (Some(tim), Some(ext)) => {
                let file_name = format!("{}{}", tim, ext);
                let uri = format!("{}/{}", link.board, file_name);
                download(&uri, &file_name, dir.clone());
            _ => {}

Now each of the download function returns a future. How can I tell the compiler to wait until all the futures created from inside a loop?

In Go, I would create a WaitGroup and wg.Add(1) after each call to download. Inside the download() function, when a download finishes I would send wg.Done() signal to indicate that that the process finished. And before main() ends, I would call wg.Wait() to instruct the program to wait for all waitgroups to finish. I'm not sure how to achieve that in async-await.

You can use join_all from the futures crate to wait until all futures from a Vec or Iterator are finished.

If you want to limit the number of futures you run concurrently, you can use FuturesUnordered instead.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.