Finlay Weber
Finlay Weber

Reputation: 4163

How to compose multiple async operation when using join_all in Rust

I have multiple async operations that are in stages. For example, let's say the first stage of async operations is making multiple requests, the second stage is parsing the results of the multiple http requests to JSON.

When using join_all, I can perform these operations in two steps.

Basically

let raw_responses = join_all(endpoints.iter().map(|endpoint| {
  self.client.get(endpoin)).send();
}).collect()).await;
let responses = join_all(raw_responses.into_iter().map(|response| response.unwrap().json::<ResultStruct>())).await;

This works. But I was wondering if there is a way to compose the two async operations and use only one join_all

Upvotes: 0

Views: 763

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71605

Yes:

let responses = join_all(endpoints.iter().map(|endpoint| async {
    let raw_response = self.client.get(endpoint).send().await;
    raw_response.unwrap().json::<ResultStruct>().await
})).await;

Upvotes: 2

Related Questions