How to tokio::join on a vector of futures

I've stared on this doc join in tokio - Rust for hours but can not figure out a way to wait on a vector of futures.

Although there is JoinSet, but it is an unstable API.

Any ideas? Thanks

It seems futures_util::future::join_all can do the job, am I correct?

I tried to use it, and my code can compile and run.

I would say that the best approach is to spawn them:

let mut handles = Vec::with_capacity(futures.len());

for fut in futures {
    handles.push(tokio::spawn(fut));
}

let mut results = Vec::with_capacity(handles.len());
for handle in handles {
    results.push(handle.await.unwrap());
}

Using join_all is also an option, but it's less efficient and has some pitfalls (e.g. it makes it easy to accidentally ignore errors).

5 Likes

Got it, I'll go back to tokio::task::spawn then. Thanks a lot for the suggestion!

Hi @alice , in your solution, how to fail all tasks immediately if any task fails? I want to fail all tasks immediately if one of them fails.

Since the JoinSet type is still unstable, you have to do that yourself. The easiest way is to wrap the vector in a struct with a destructor that calls abort on all of them.

Good idea! Thanks

I would say that the best approach is to spawn them

There is still a difference between spawn and join: the second one is not parallel, and it could matter a lot, because it would allow for example using mutable objects without needing to encapsulate them inside a Mutex.
Maybe it doesn't matter in most cases, but It could be worth to mention in this thread.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.