Vec of Futures to Future of Vec?

Say i have something like:

let keys: Vec<Key> = vec![key1, key2, key3];
let data = keys
    .into_iter()
    .map(Data::load)
    .collect::<Result<Vec<Data>, _>>?;

Now suppose I convert Data::load to an async fn. Is there any nice way to rewrite the above collect line above to somehing that lets me await a single Result<Vec<Data>, E> ?

Can it be done with the std library (rust 1.48.0), or with the futures crate, or do I have to rewrite it as a loop?

Perhaps something like this works (it compiles, but I didn’t test the behavior):

let data = stream::iter(keys)
    .then(Data::async_load)
    .try_collect::<Vec<Data>>()
    .await?;

(playground)

Thanks! That seems to work fine in my real case as well. It requires a direct dependency on futures 0.3, but that's ok.

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.