0

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

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37

1 Answers1

2

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;
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • I was of the opinion doing the `.await` within the join all will actually execute things sequentially. As I understand Futures are inert unless the .await is called. So If I am calling tis within the join_all, then it is different from only calling it outside and on the reults of join_all. Myabe I am wrong – Finlay Weber Dec 12 '22 at 16:16
  • 1
    @FinlayWeber It will execute the (send, json) sequentially. This is forced. But each future is still executed in parallel to the others. In fact, this is even more async than your version: instead of starting executing the jsons after all futures have completed, this start for each future immediately. – Chayim Friedman Dec 12 '22 at 16:17